connecting dots

JS | Array method(배열 메소드) 정리 본문

TIL

JS | Array method(배열 메소드) 정리

dearsuhyun 2024. 7. 25. 01:18

배열 메소드

메소드란 ?
객체의 속성 중 하나로, 함수 형태로 정의되어 객체의 동작(behavior)을 나타내는 속성입니다.
JavaScript에서 배열 메서드는 배열 객체의 프로토타입에 정의된 함수로, 배열을 조작하거나 배열의 정보를 반환하는 데 사용됩니다.
JavaScript 배열도 객체이며, 배열에 사용되는 메서드는 배열의 프로토타입에 정의되어 있습니다. 

 

간단 정리

정적 메서드
1. Array.from: 유사 배열 객체나 반복 가능한 객체를 배열로 변환합니다.
2. Array.isArray: 주어진 값이 배열인지 여부를 확인합니다.

인스턴스 메서드
1. at: 배열에서 지정된 인덱스에 있는 요소를 반환합니다.
2. concat: 두 개 이상의 배열이나 값을 결합하여 새로운 배열을 반환합니다.
3. every: 배열의 모든 요소가 주어진 조건을 만족하는지 확인합니다.
4. filter: 주어진 조건을 만족하는 모든 요소를 포함하는 새로운 배열을 반환합니다.
5. find: 주어진 조건을 만족하는 첫 번째 요소를 반환합니다.
6. findIndex: 주어진 조건을 만족하는 첫 번째 요소의 인덱스를 반환합니다.
7. forEach: 배열의 각 요소에 대해 주어진 함수를 실행합니다.
8. includes: 배열에 특정 요소가 포함되어 있는지 확인합니다.
9. indexOf: 배열에서 특정 요소의 첫 번째 인덱스를 반환합니다.
10. join: 배열의 모든 요소를 문자열로 결합하여 반환합니다.
11. keys: 배열의 각 인덱스를 포함하는 배열 반복자 객체를 반환합니다.
12. map: 배열의 각 요소를 변환한 새로운 배열을 반환합니다.
13. pop: 배열의 마지막 요소를 제거하고 그 요소를 반환합니다.
14. push: 배열의 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환합니다.
15. reduce: 배열의 각 요소를 누적하여 단일 값으로 줄입니다.
16. reverse: 배열의 요소 순서를 반대로 바꿉니다.
17. shift: 배열의 첫 번째 요소를 제거하고 그 요소를 반환합니다.
18. slice: 배열의 일부분을 선택하여 새로운 배열로 반환합니다.
19. some: 배열의 일부 요소가 주어진 조건을 만족하는지 확인합니다.
20. sort: 배열의 요소를 정렬합니다.
21. splice: 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
22. unshift: 배열의 앞에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환합니다.
23. values: 배열의 각 요소 값을 포함하는 배열 반복자 객체를 반환합니다.

인스턴스 속성
1. length: 배열의 요소 개수를 나타냅니다.

 

 

정적 메소드

Array.from()

유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 배열로 변환하는 데 사용됩니다.

이를 사용하면 문자열, Set, Map 같은 객체를 실제 배열로 만들 수 있습니다.

이 메서드는 새로운 배열 인스턴스를 생성하며, 배열의 모든 요소를 얕게 복사합니다.

 

1. 문자열을 배열로 변환

const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']

 

2. Array.from()의 매핑 함수(배열의 각 요소를 변환하거나 처리하는 함수)

const numbers = [1, 2, 3, 4];
const doubled = Array.from(numbers, x => x * 2);
console.log(doubled); // [2, 4, 6, 8]

Array.isArray()

주어진 값이 배열인지 여부를 확인하는 데 사용됩니다.

이 메서드는 값이 배열이면 true를, 그렇지 않으면 false를 반환합니다.

console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({ a: 1, b: 2 })); // false(객체)
console.log(Array.isArray('hello')); // false(문자열)
console.log(Array.isArray(null)); // false(null)
function checkArguments() {
  console.log(Array.isArray(arguments)); // false(유사배열객체이지만 배열은 아님)
}
checkArguments(1, 2, 3);

 

cf. 유사배열객체

배열처럼 length 속성을 가지고 있고 인덱스로 요소에 접근할 수 있지만, 실제 배열은 아닌 객체를 말합니다.

유사 배열 객체는 배열의 메서드(push, pop, forEach 등)를 직접 사용할 수 없습니다.

대신 Array 메서드를 활용하거나 Array.from을 사용하여 실제 배열로 변환할 수 있습니다.

function example() {
  console.log(arguments);
  console.log(arguments.length); // 인수의 개수
  console.log(arguments[0]); // 첫 번째 인수
}

example('a', 'b', 'c');
// 출력:
// { '0': 'a', '1': 'b', '2': 'c' }
// 3
// 'a'

 

cf. arguments 객체

자바스크립트에서 전달된 인수와 매개변수의 개수는 서로 같지 않아도 됩니다.

매개변수의 개수보다 인수가 더 적을 경우 넘어오지 않은 값은 undefinded로 표시됩니다.

매개변수의 개수보다 초과된 인수는 무시됩니다.

function a(ar1, ar2) {
  console.log(ar1, ar2);
}

print() // undefined undefinded
print('a'); // a undefined
print('a', 'b') // a b
print('a', 'b', 'c') // a b

 

즉, 함수에 넘어오는 인자가 몇 개이든 상관이 없기 때문에 함수가 동작하기 전에 인수의 개수를 확인하여 동작을 다르게 해야 합니다. 이를 위해 인수를 저장해 놓은 공간이 바로 arguments입니다.

arguments란, 함수에 전달되는 인수들을 배열 형태로 나타낸 객체입니다. arguments는 변수 이름이 아닌 키워드이며, 형태만 배열이기 때문에 배열 메소드(map, forEach 등)를 사용하면 에러가 뜹니다.

function a(ar1, ar2, ar3) {
  console.log(arguments[0])
  console.log(arguments[1])
  console.log(arguments[2])
}
print('a', 'b', 'c')

 

arguments 요소는 재할당도 가능합니다.

function a(ar1, ar2, ar3) {
  arguments[0] = 'z';
  console.log(arguments[0]) // z
  console.log(arguments[1]) // b
  console.log(arguments[2]) // c
}
print('a','b','c')

 

화살표 함수에서의 arguments

화살표 함수에서 arguments를 출력하면 오류가 뜹니다. 

const arrowFunc = () => {
  console.log(arguments); // ReferenceError: arguments is not defined
};

arrowFunc(1, 2, 3);

 

따라서 화살표 함수 내부에서 사용하려면 화살표 함수가 호출되는 외부 함수의 arguments 객체를 참조해야 합니다.

function outerFunc() {
  const arrowFunc = () => {
    console.log(arguments); // 외부 함수(outerFunc())의 arguments 객체를 참조
  };
  arrowFunc();
}

outerFunc('a', 'b', 'c'); // ['a', 'b', 'c'] 출력

 

화살표 함수에서 인수를 처리하는 방법으로 rest 파라미터를 사용할 수 있습니다.

이는 화살표 함수에 전달된 모든 인수를 배열로 받는 방법입니다.

const arrowFunc = (...args) => {
  console.log(args); // ['a', 'b', 'c'] 출력
};

arrowFunc('a', 'b', 'c');

 

cf. REST 파라미터

rest 파라미터는 함수의 인수 목록에서 사용되어, 함수에 전달된 인수들을 배열로 수집합니다.

이는 주로 함수 정의 시 사용됩니다.

function exampleFunc(...args) {
  console.log(args); // args는 인수들이 담긴 배열
}

exampleFunc(1, 2, 3); // [1, 2, 3] 출력

 

** 전개연산자(...)는 겉모습은 같지만 배열이나 객체 --> 개별요소로 펼칠 때 사용합니다.


Array.at()

배열에서 특정 인덱스에 있는 요소를 반환합니다.

이 메서드는 양수와 음수 인덱스 모두 지원하므로, 배열의 끝에서부터 요소를 쉽게 접근할 수 있습니다.

음수 인덱스는 배열의 마지막 요소부터 역순으로 접근할 수 있도록 합니다.

 

1. 양수 인덱스

const array = [10, 20, 30, 40, 50];

console.log(array.at(0)); // 10 (첫 번째 요소)
console.log(array.at(2)); // 30 (세 번째 요소)
console.log(array.at(4)); // 50 (다섯 번째 요소)

 

2. 음수 인덱스

const array = [10, 20, 30, 40, 50];

console.log(array.at(-1)); // 50 (마지막 요소)
console.log(array.at(-2)); // 40 (뒤에서 두 번째 요소)
console.log(array.at(-5)); // 10 (첫 번째 요소, -5는 배열 길이만큼 더한 것과 동일)

 

음수 인덱스를 지원하기 때문에 기존 방식보다 배열의 끝에서부터 접근하는 것이 쉬워진다는 장점이 있습니다.

// 기존방식 
const array = [10, 20, 30, 40, 50];

console.log(array[0]); // 10 (첫 번째 요소)
console.log(array[array.length - 1]); // 50 (마지막 요소)
console.log(array[array.length - 2]); // 40 (뒤에서 두 번째 요소)

Array.concat()

배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

기존 배열을 변경하지 않습니다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3); // ["a", "b", "c", "d", "e", "f"]
const array1 = [1, 2];
const array2 = [3, 4];
const array3 = [5, 6];

const newArray = array1.concat(array2, array3);
console.log(newArray); // [1, 2, 3, 4, 5, 6]
console.log(array1); // [1, 2] (원본 배열은 변경되지 않음)
console.log(array2); // [3, 4] (원본 배열은 변경되지 않음)
console.log(array3); // [5, 6] (원본 배열은 변경되지 않음)

Array.every()

배열의 모든 요소가 주어진 조건을 만족하는지 확인하는 데 사용됩니다.

이 메서드는 배열의 각 요소에 대해 제공된 테스트 함수를 호출하며, 모든 요소가 해당 조건을 만족하면 true를 반환하고, 하나라도 조건을 만족하지 않으면 false를 반환합니다.

 

1. 기본

const numbers = [2, 4, 6, 8, 10];
const allEven = numbers.every(function(element) {
  return element % 2 === 0;
});
console.log(allEven); // true

const numbers = [1, 2, 3, 4, 5, 11];
const allLessThanTen = numbers.every(element => element < 10);
console.log(allLessThanTen); // false

 

2. 화살표 함수

const numbers = [1, 2, 3, 4, 5];

const allPositive = numbers.every(element => element > 0);

console.log(allPositive); // true

 

3. 객체

const people = [
  { name: 'John', age: 20 },
  { name: 'Jane', age: 25 },
  { name: 'Jack', age: 30 }
];

const allAdults = people.every(person => person.age >= 18);

console.log(allAdults); // true

Array.filter()

배열의 각 요소를 순회하며 제공된 테스트 함수(콜백 함수)를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

이 메서드는 원본 배열을 변경하지 않습니다.

 

1. 기본

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(element) {
  return element % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6]

 

2. 화살표 함수

const numbers = [-1, 0, 1, 2, -2, 3];
const positiveNumbers = numbers.filter(element => element > 0);

console.log(positiveNumbers); // [1, 2, 3]

 

3. 조건에 맞는 객체 추출

const people = [
  { name: 'John', age: 17 },
  { name: 'Jane', age: 20 },
  { name: 'Jack', age: 15 },
  { name: 'Jill', age: 22 }
];
const adults = people.filter(person => person.age >= 18);

console.log(adults); 
// [{ name: 'Jane', age: 20 }, { name: 'Jill', age: 22 }]

 

4. 특정 문자열 포함

const fruits = ['apple', 'banana', 'grape', 'pear'];
const fruitsWithA = fruits.filter(fruit => fruit.includes('a'));

console.log(fruitsWithA); // ['apple', 'banana', 'grape']

Array.find()

배열의 각 요소에 대해 제공된 테스트 함수를 호출하여, 조건을 만족하는 첫 번째 요소를 반환합니다.

조건을 만족하는 요소가 없으면 undefined를 반환합니다.

 

1. 기본

const numbers = [1, 2, 3, 4, 5, 6];

const firstEven = numbers.find(function(element) {
  return element % 2 === 0;
});

console.log(firstEven); // 2

 

2. 객체

const people = [
  { name: 'John', age: 17 },
  { name: 'Jane', age: 20 },
  { name: 'Jack', age: 15 },
  { name: 'Jill', age: 22 }
];

const firstAdult = people.find(person => person.age >= 18);

console.log(firstAdult); 
// { name: 'Jane', age: 20 }

 

3. 조건을 만족하는 요소가 없는 경우

const numbers = [1, 2, 3, 4, 5];

const firstGreaterThanTen = numbers.find(element => element > 10);

console.log(firstGreaterThanTen); // undefined

Array.findIndex()

배열의 각 요소에 대해 제공된 테스트 함수를 호출하여, 조건을 만족하는 첫 번째 요소의 인덱스를 반환합니다.

조건을 만족하는 요소가 없으면 -1을 반환합니다.

 

1. 기본

const numbers = [1, 2, 3, 4, 5, 6];

const firstEvenIndex = numbers.findIndex(function(element) {
  return element % 2 === 0;
});

console.log(firstEvenIndex); // 1

 

2. 객체

const people = [
  { name: 'John', age: 17 },
  { name: 'Jane', age: 20 },
  { name: 'Jack', age: 15 },
  { name: 'Jill', age: 22 }
];

const firstAdultIndex = people.findIndex(person => person.age >= 18);

console.log(firstAdultIndex); // 1

 

3. 조건을 만족하는 요소가 없을 경우

const numbers = [1, 2, 3, 4, 5];

const firstGreaterThanTenIndex = numbers.findIndex(element => element > 10);

console.log(firstGreaterThanTenIndex); // -1

Array.forEach()

배열의 각 요소에 대해 주어진 함수를 한 번씩 실행합니다.

이 메서드는 반복문과 비슷한 기능을 하며, 배열을 순회하면서 각 요소에 대해 특정 작업을 수행할 때 유용합니다.

 

주요 특징

 

1. 반환 값이 없음: forEach()는 배열의 각 요소에 대해 함수를 실행하지만, 값을 반환하지 않습니다.

2. 변경 가능: forEach()는 원본 배열의 요소를 변경할 수 있습니다.

3. 콜백 함수: forEach()는 콜백 함수를 인수로 받으며, 이 함수는 배열의 각 요소에 대해 호출됩니다.

콜백 함수는 세 가지 인수를 받을 수 있습니다: 현재 요소, 현재 요소의 인덱스, 배열 자체.

 

array.forEach(function(element, index, array) {
  // 실행할 코드
});

element: 현재 처리 중인 배열 요소.

index (선택적): 현재 처리 중인 배열 요소의 인덱스.

array (선택적): forEach()를 호출한 배열.

 

1. 기본

const array = [1, 2, 3, 4, 5];

array.forEach(function(element) {
  console.log(element);
});
// 출력:
// 1
// 2
// 3
// 4
// 5

 

2. 배열과 함께 사용

const array = ['a', 'b', 'c'];

array.forEach(function(element, index, array) {
  console.log('요소:', element);
  console.log('인덱스:', index);
  console.log('배열:', array);
});
// 출력:
// 요소: a
// 인덱스: 0
// 배열: ['a', 'b', 'c']
// 요소: b
// 인덱스: 1
// 배열: ['a', 'b', 'c']
// 요소: c
// 인덱스: 2
// 배열: ['a', 'b', 'c']

 

3. 배열 요소 변경

const array = [1, 2, 3, 4, 5];

array.forEach(function(element, index, array) {
  array[index] = element * 2;
});

console.log(array); // [2, 4, 6, 8, 10]
각 단계 설명


1. 초기 배열: [1, 2, 3, 4, 5]
2. 첫 번째 순회 (index = 0):
element: 1
index: 0
array: [1, 2, 3, 4, 5]
array[0] = 1 * 2 -> array는 이제 [2, 2, 3, 4, 5]
3. 두 번째 순회 (index = 1):
element: 2
index: 1
array: [2, 2, 3, 4, 5]
array[1] = 2 * 2 -> array는 이제 [2, 4, 3, 4, 5]
4. 세 번째 순회 (index = 2):
element: 3
index: 2
array: [2, 4, 3, 4, 5]
array[2] = 3 * 2 -> array는 이제 [2, 4, 6, 4, 5]
5. 네 번째 순회 (index = 3):
element: 4
index: 3
array: [2, 4, 6, 4, 5]
array[3] = 4 * 2 -> array는 이제 [2, 4, 6, 8, 5]
6. 다섯 번째 순회 (index = 4):
element: 5
index: 4
array: [2, 4, 6, 8, 5]
array[4] = 5 * 2 -> array는 이제 [2, 4, 6, 8, 10]
7. 최종 배열: [2, 4, 6, 8, 10]

 

4. 객체 배열 처리

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jack', age: 35 }
];

people.forEach(function(person) {
  console.log(person.name + ' is ' + person.age + ' years old');
});
// 출력:
// John is 25 years old
// Jane is 30 years old
// Jack is 35 years old

Array.includes()

배열이 특정 요소를 포함하고 있는지 여부를 확인합니다.

이 메서드는 포함 여부를 확인할 요소를 인수로 받아, 배열에 해당 요소가 존재하면 true, 그렇지 않으면 false를 반환합니다.

const numbers = [1, 2, 3, 4, 5];

console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
const numbers = [1, 2, 3, 4, 5];

console.log(numbers.includes(3, 3)); // false (인덱스 3부터 검색 시작)
console.log(numbers.includes(4, 3)); // true (인덱스 3부터 검색 시작)
const arrayWithNaN = [1, 2, NaN, 4, 5];

console.log(arrayWithNaN.includes(NaN)); // true

Array.indexOf()

배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환합니다.

지정된 요소가 배열에 존재하지 않으면 -1을 반환합니다. 이 메서드는 배열을 앞에서부터 순차적으로 검색합니다.

 

- 문법

array.indexOf(searchElement[, fromIndex])
// fromIndex: 검색을 시작할 인덱스, 기본값은 0

 

const numbers = [1, 2, 3, 4, 3, 5];

console.log(numbers.indexOf(3)); // 2 (첫 번째 3의 인덱스)
console.log(numbers.indexOf(6)); // -1 (6은 배열에 없음)
const numbers = [1, 2, 3, 4, 3, 5];

console.log(numbers.indexOf(3, 3)); // 4 (인덱스 3부터 검색 시작, 두 번째 3의 인덱스)
console.log(numbers.indexOf(3, 5)); // -1 (인덱스 5부터 검색 시작, 3은 없음)

Array.join()

배열의 모든 요소를 연결해 하나의 문자열로 반환합니다.

(length가 0이라면 빈 문자열을 반환합니다.)
매개변수 = 각 요소를 구분할 문자열 지정(생략시 쉼표로 구분)

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // "Fire,Air,Water"
console.log(elements.join('')); // "FireAirWater"
console.log(elements.join('-')); // "Fire-Air-Water"

Array.keys()

배열의 위치(인덱스)를 하나씩 나열해주는 도구입니다.

이 객체를 사용하면 배열의 모든 인덱스를 순서대로 쉽게 반복할 수 있습니다.

const arr = ['a', 'b', 'c'];
const iterator = arr.keys(); // 배열의 인덱스를 나열하는 반복자 생성

for (let key of iterator) {
// for...of 반복문을 사용하여 iterator 객체를 하나씩 순회합니다.
// key는 배열의 각 위치를 나타내는 숫자입니다.
  console.log(key); // 0, 1, 2 출력
}

 

- for...of 사용

const array = ['a', 'b', 'c'];

for (const key of array.keys()) {
  console.log(key); // 0, 1, 2 (순서대로 인덱스 출력)
}

 

- 인덱스 사용

const fruits = ['apple', 'banana', 'cherry'];
const keys = fruits.keys();

for (const key of keys) {
  console.log(`Index: ${key}, Value: ${fruits[key]}`);
  // 출력:
  // Index: 0, Value: apple
  // Index: 1, Value: banana
  // Index: 2, Value: cherry
}

Array.map()

배열의 각 요소를 변환하여 새로운 배열을 생성하는 데 사용됩니다.

map() 메서드는 원본 배열을 변경하지 않고, 각 요소를 변환한 결과로 새로운 배열을 반환합니다.

 

주요 특징

 

1. 새로운 배열 생성: map() 메서드는 배열의 각 요소를 변환한 결과로 새로운 배열을 반환합니다.

2. 원본 배열 유지: 원본 배열은 변경되지 않습니다.

3. 콜백 함수: map() 메서드는 콜백 함수를 인수로 받으며, 이 함수는 배열의 각 요소에 대해 호출됩니다. 콜백 함수는 세 가지 인수를 받을 수 있습니다: 현재 요소, 현재 요소의 인덱스, 배열 자체.

const newArray = array.map(function(element, index, array) {
  // 새로운 값 반환
});

 

element: 현재 처리 중인 배열 요소의 값.

index (선택적): 현재 처리 중인 배열 요소의 인덱스.

array (선택적): map() 메서드를 호출한 배열.

 

1. 기본

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(element) {
  return element * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (원본 배열은 변경되지 않음)

 

2. 배열과 함께

const numbers = [1, 2, 3, 4, 5];
const mapped = numbers.map(function(element, index, array) {
  return element + index;
});

console.log(mapped); // [1, 3, 5, 7, 9]

 

3. 객체 배열 처리

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jack', age: 35 }
];

const names = people.map(function(person) {
  return person.name;
});

console.log(names); // ['John', 'Jane', 'Jack']

 

cf.forEach()와 map()의 차이점

 forEach():

 반환 값이 없습니다.

 배열의 각 요소에 대해 주어진 함수를 실행합니다.

 원본 배열을 변경할 수 있습니다.

 map():

 배열의 각 요소를 변환하여 새로운 배열을 반환합니다.

 원본 배열은 변경되지 않습니다.


Array.pop()

배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

빈 배열일 경우 undefined를 반환합니다.

const array = [1, 2, 3, 4];
console.log(array.pop()); // 4
console.log(array); // [1, 2, 3]

Array.push()

배열의 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환합니다.

매개변수 = 배열 끝에 추가할 요소들

const array = ["apple", "banana"];
console.log(array.push("mango")); // 3
console.log(array) // ["apple", "banana", mango"];

Array.reduce()

배열의 각 요소에 대해 주어진 함수를 실행하고, 하나의 결과값을 반환합니다.

 

- 문법

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

callback: 배열의 각 요소에 대해 실행할 함수로, 다음 네 가지 인수를 받습니다:

accumulator: 누산기의 누적 값.

currentValue: 현재 처리 중인 배열 요소.

index (선택적): 현재 처리 중인 배열 요소의 인덱스.

array (선택적): reduce()를 호출한 배열.

initialValue (선택적): 초기 누산기 값. 제공하지 않으면 배열의 첫 번째 요소가 초기 값으로 사용됩니다.

 

cf. 누산기 비유
누산기를 저금통이라고 생각해보세요. 저금통에 처음에는 0원이 들어있습니다.
동전(배열의 각 요소)을 하나씩 저금통에 넣으면서 저금통의 총 금액이 늘어나게 됩니다.
이 과정에서 저금통이 바로 누산기입니다.

 

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 15

 

- 객체 배열의 특정 값 합산

const items = [
  { name: 'apple', price: 10 },
  { name: 'banana', price: 20 },
  { name: 'cherry', price: 30 }
];

const totalPrice = items.reduce((accumulator, item) => {
  return accumulator + item.price;
}, 0);

console.log(totalPrice); // 60

 

- 배열 평탄화(중첩된 배열을 하나의 배열로 만들기)

const nestedArray = [[1, 2], [3, 4], [5, 6]];

const flatArray = nestedArray.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);

console.log(flatArray); // [1, 2, 3, 4, 5, 6]

Array.reverse()

배열의 순서를 반전하고, 반전된 배열을 반환합니다.

원본 배열 자체를 변경합니다.

const array1 = ['one', 'two', 'three']; 
console.log('array1:', array1); // array1: (3) ['one', 'two', 'three']

const reversed = array1.reverse();
console.log('reversed:', reversed); // reversed: (3) ['three', 'two', 'one']
console.log('array1:', array1); // array1: (3) ['three', 'two', 'one']

 

만약 원본 배열이 변경되는걸 막고 싶다면, '....' 전개 연산자를 이용해 복사본을 만든 후 reverse 합니다.

const array1 = ['one', 'two', 'three'];
const reversed = [...array1].reverse();

console.log('array1:', array1); 
// 출력: array1: ['one', 'two', 'three']

console.log('reversed:', reversed); 
// 출력: reversed: ['three', 'two', 'one']

 

 

cf. 전개연산자의 기능

1. 배열 복사 및 합치기

// 배열 복사
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // [1, 2, 3]

// 배열 합치기
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

 

2. 객체 복사 및 속성 병합

// 객체 복사
const originalObject = { a: 1, b: 2 };
const copiedObject = { ...originalObject };
console.log(copiedObject); // { a: 1, b: 2 }

// 객체 병합
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // { a: 1, b: 3, c: 4 }

 

3. 함수 호출 시 인수로 전달

// 배열을 함수의 인자로 전달
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

 

4. 문자열을 개별 문자로 분해

const str = "hello";
const charArray = [...str];

console.log(charArray); // ['h', 'e', 'l', 'l', 'o']

Array.shift()

배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다.

빈 배열일 경우 undefined를 반환합니다.

const array = [1, 2, 3, 4];
console.log(array.shift()); // 1
console.log(array); // [2, 3, 4]

Array.slice()

원본 배열을 변경하지 않고, 배열의 일부를 복사하여 새로운 배열을 반환합니다.

slice 메서드는 시작 인덱스와 종료 인덱스를 받아, 시작 인덱스에서 종료 인덱스 전까지의 요소들을 포함하는 새로운 배열을 만듭니다.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2)); // ["camel", "duck", "elephant"] 

console.log(animals.slice(2, 4)); // ["camel", "duck"] 

console.log(animals.slice(1, 5)); // ["bison", "camel", "duck", "elephant"] 

console.log(animals.slice(-2)); // ["duck", "elephant"] 
// 끝에서 두 번째 요소에서 시작하여 끝까지의 요소를 복사합니다.

console.log(animals.slice(2, -1)); // ["camel", "duck"]  
// 인덱스 2에서 시작하여 끝에서 첫 번째 요소 전까지의 요소를 복사합니다.

console.log(animals.slice()); // ["ant", "bison", "camel", "duck", "elephant"]
// 배열 전체를 복사합니다.

Array.splice()

배열의 기존 요소를 삭제, 교체하거나 새 요소를 추가하여 배열의 내용을 변경하는 데 사용됩니다.

이 메서드는 원본 배열을 변경하며, 삭제된 요소들을 새로운 배열로 반환합니다.

 

매개변수

splice(인덱스(index), 제거할 요소 개수(deleteCount), 추가될 요소(item))

 

item을 지정하지 않으면 splice는 요소 제거만 수행합니다.

array.splice(시작 인덱스, 삭제 개수, 추가할 아이템들);

const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(array1.splice(2, 3)); // 반환값 : [3, 4, 5]
console.log(array1); // 기존 array1 : [1, 2, 6, 7, 8, 9, 10]

const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
array2.splice(2, 3, "a", "b"); 
// ↑ 2번째 인덱스부터 3개의 요소를 삭제하고 그 자리에 "a", "b" 추가
console.log(array2); // [1, 2, 'a', 'b', 6, 7, 8, 9, 10]

 

cf. array.slice()와 array.splice()의 차이점

  slice splice
목적 배열의 일부를 복사하여 새로운 배열을 생성  배열의 요소를 추가, 제거 또는 교체
원본 배열 변경 여부  X O
반환 값 새로운 배열 (원본 배열의 일부 요소를 포함). 제거된 요소들을 새로운 배열로 반환
인자 시작 인덱스 (포함)
종료 인덱스 (포함되지 않음, 선택적)
시작 인덱스.
제거할 요소의 수.
추가할 요소 (선택적).

Array.some()

 배열의 각 요소를 테스트하는 함수가 적어도 하나의 요소에 대해 참(true)을 반환하는지 확인합니다. 즉, 배열 내에 주어진 조건을 만족하는 요소가 하나라도 있는지를 확인하는 메서드입니다. 조건을 만족하는 요소가 있으면 true를 반환하고, 없으면 false를 반환합니다.

 

주요 특징

 

1. 콜백 함수: 배열의 각 요소에 대해 테스트할 함수를 인수로 받습니다.

2. 반환 값: 배열의 요소 중 하나라도 조건을 만족하면 true, 그렇지 않으면 false를 반환합니다.

3. 즉시 종료: 조건을 만족하는 요소를 찾으면 나머지 요소를 검사하지 않고 즉시 실행을 종료합니다.

 

1. 기본

const array = [1, 2, 3, 4, 5];

const hasEvenNumber = array.some(function(element) {
  return element % 2 === 0;
});

console.log(hasEvenNumber); // true

 

2. 화살표 함수 사용

const array = [1, -2, 3, 4, 5];

const hasNegativeNumber = array.some(element => element < 0);

console.log(hasNegativeNumber); // true

 

3. 객체 배열에서 조건 확인

const people = [
  { name: 'John', age: 17 },
  { name: 'Jane', age: 20 },
  { name: 'Jack', age: 15 }
];

const hasAdult = people.some(person => person.age >= 18);

console.log(hasAdult); // true

Array.sort()

배열의 요소를 정렬합니다.

기본적으로, 요소를 문자열로 변환한 후 유니코드 코드 포인트 순서에 따라 정렬합니다.

이 메서드는 원본 배열을 변경합니다.

 

1. 기본

const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();

console.log(fruits); // ['apple', 'banana', 'cherry']

 

2. 숫자 배열 정렬

Array.sort() 메서드는 기본적으로 요소를 문자열로 변환한 후 유니코드 코드 포인트 순서에 따라 정렬합니다. 이 때문에 숫자 배열을 정렬할 때 의도한 대로 정렬되지 않을 수 있습니다.

const numbers = [10, 5, 40, 25, 1000];
numbers.sort();
console.log(numbers); // [10, 1000, 25, 40, 5]

 

숫자 배열을 올바르게 정렬하려면 비교 함수를 제공해야 합니다. 비교 함수는 두 개의 요소를 인수로 받아 이들의 정렬 순서를 결정합니다.

// 오름차순
// 숫자를 작은 값에서 큰 값으로 정렬하려면 비교 함수에서 a - b를 반환합니다.
const numbers = [10, 5, 40, 25, 1000];
numbers.sort((a, b) => a - b);
console.log(numbers); // [5, 10, 25, 40, 1000]

// 내림차순
// 숫자를 큰 값에서 작은 값으로 정렬하려면 비교 함수에서 b - a를 반환합니다.
const numbers = [10, 5, 40, 25, 1000];
numbers.sort((a, b) => b - a);
console.log(numbers); // [1000, 40, 25, 10, 5]

 

cf. 비교 함수 설명

비교 함수는 sort 메서드가 배열의 요소를 비교하여 정렬 순서를 결정하는 방법을 정의합니다.

비교 함수는 다음과 같은 값을 반환해야 합니다:

 

음수 값: ab보다 작음을 의미합니다. 정렬 시 ab보다 앞에 위치합니다.

0: ab가 같음을 의미합니다. 정렬 시 ab의 순서는 변경되지 않습니다.

양수 값: ab보다 큼을 의미합니다. 정렬 시 ab보다 뒤에 위치합니다.

 

3. 객체 배열 정렬

const items = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Jack', age: 35 }
];

// 나이(age)를 기준으로 오름차순 정렬
items.sort((a, b) => a.age - b.age);

console.log(items);
// [
//   { name: 'Jane', age: 25 },
//   { name: 'John', age: 30 },
//   { name: 'Jack', age: 35 }
// ]

Array.unshift()

메서드는 배열의 맨 앞에 하나 이상의 요소를 추가하고, 새로운 길이를 반환합니다.

이 메서드는 원본 배열을 변경합니다.

const array = [3, 4, 5];
const newLength = array.unshift(1, 2);

console.log(array); // [1, 2, 3, 4, 5]
console.log(newLength); // 5

Array.values()

배열의 요소들을 하나씩 순서대로 꺼내올 수 있는 도구를 제공합니다.

이 도구를 사용하면 배열의 첫 번째 요소부터 마지막 요소까지 차례로 접근할 수 있습니다.

const array = ['a', 'b', 'c'];
const iterator = array.values();

console.log(iterator.next().value); // 'a' (첫 번째 요소)
console.log(iterator.next().value); // 'b' (두 번째 요소)
console.log(iterator.next().value); // 'c' (세 번째 요소)

 

쉽게 설명하기
생각해보세요, 배열은 여러 개의 상자가 줄지어 놓여 있는 것과 같습니다. 각 상자 안에는 하나의 물건이 들어있습니다.
Array.values()는 이 상자들을 차례차례 열어서 안에 있는 물건을 꺼낼 수 있는 도구를 줍니다.

1. 상자 배열: 상자에 ‘a’, ‘b’, ‘c’라는 물건이 들어있다고 생각해보세요.
2. 도구 사용: Array.values()라는 도구를 사용하면, 첫 번째 상자부터 마지막 상자까지 순서대로 열 수 있습니다.
3. 물건 꺼내기: 도구를 사용하여 첫 번째 상자를 열면 ‘a’, 두 번째 상자를 열면 ‘b’, 세 번째 상자를 열면 ‘c’가 나옵니다.

 

- for...of 사용

const array = ['a', 'b', 'c'];

for (const value of array.values()) {
  console.log(value); // 차례대로 'a', 'b', 'c'가 출력됩니다.
}

 

인스턴스 속성

Array.length()

JavaScript에서 배열의 길이(즉, 배열에 포함된 요소의 개수)를 나타내는 속성입니다.

배열의 길이를 읽거나 설정할 때 사용됩니다.

const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length); // 3
// 길이 늘이기
const fruits = ['apple', 'banana'];
fruits.length = 5;
console.log(fruits); // ['apple', 'banana', undefined, undefined, undefined]

// 길이 줄이기
const fruits = ['apple', 'banana', 'cherry'];
fruits.length = 2;
console.log(fruits); // ['apple', 'banana']

 

 

반응형