배열 메서드는 배열 데이터를 처리하기 위해 다양한 기능을 제공한다.
배열 메서드는 크게 변경 메서드(Mutable)와 비변경 메서드(Immutable)로 나눌 수 있다.
이번 포스팅에서는 다양한 변경 메서드와 비변경 메서드에 대해 알아보려 한다.
변경 메서드는 배열의 원본 데이터 자체를 변경하는 메서드이다. 따라서 주의해서 사용해야 한다.
let fruits = ['Apple', 'Banana'];
fruits.push('Cherry');
console.log(fruits); // (3) ['Apple', 'Banana', 'Cherry']
let fruits = ['Apple', 'Banana', 'Cherry'];
let lastFruit = fruits.pop();
console.log(fruits); // ['Apple', 'Banana']
console.log(lastFruit); // 'Cherry'
let fruits = ['Apple', 'Banana', 'Cherry'];
let firstFruit = fruits.shift();
console.log(fruits); // ['Banana', 'Cherry']
console.log(firstFruit); // 'Apple'
let fruits = ['Banana', 'Cherry'];
fruits.unshift('Apple');
console.log(fruits); // (3) ['Apple', 'Banana', 'Cherry']
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.splice(1, 1, 'Blueberry');
console.log(fruits); // ['Apple', 'Blueberry', 'Cherry']
sort():
유니코드 코드 포인트 순으로 오름차순 정렬
let fruits = ['Banana', 'Apple', 'Cherry'];
fruits.sort(); // 알파벳 순으로 정렬
console.log(fruits); // ['Apple', 'Banana', 'Cherry']
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); // 숫자 정렬
console.log(numbers); // [1, 2, 3, 4, 5]
위 표와 코드를 기반으로 살펴보았을 때, .sort((a, b) => a - b); 는 오름차순 정렬, .sort((a,b) => b - a);는 내림차순 정렬을 뜻한다는 걸 알 수 있다.
그리고 숫자 뿐만 아니라 .length를 통해 문자열의 길이에 따라 오름차순/내림차순 정렬을 할 수도 있다.
비변경 메서드는 배열 원본을 변경하지 않고, 새로운 배열을 반환하거나 값을 반환하는 메서드이다.
let fruits = ['Apple', 'Banana'];
let moreFruits = ['Cherry', 'Date'];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // ['Apple', 'Banana', 'Cherry', 'Date']
let fruits = ['Apple', 'Banana', 'Cherry'];
let citrus = fruits.slice(1, 3); // 1번 인덱스부터 3번 인덱스 앞까지(2번)
console.log(citrus); // ['Banana', 'Cherry']
let fruits = ['Apple', 'Banana', 'Cherry'];
let fruitString = fruits.join(', '); // 요소 사이에 ', '를 넣어주겠다는 뜻
console.log(fruitString); // 'Apple, Banana, Cherry'
let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits.includes('Banana')); // true
console.log(fruits.includes('Date')); // false
let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits.indexOf('Banana')); // 1
console.log(fruits.indexOf('Date')); // -1 (배열 내에 특정 요소가 없으면 -1 반환)
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element)); // a b c
let numbers = [1, 2, 3];
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2, 4]
변경 메서드의 경우 원본 데이터 자체를 변경하는 메서드이기에 아주 주의해서 사용해야 한다.
아래 사이트를 통해 배열 메서드가 변경 메서드인지 비변경 메서드인지 쉽게 확인할 수 있다.
https://doesitmutate.xyz/