배열 27

자바스크립트에서 배열이라는 타입은 존재하지 않는다. 배열은 객체 타입이다.
배열의 생성자 함수는 Array 이며, 배열의 프로토타입 객체는 Array.prototype 이다.
Array.prototype은 배열을 위한 빌트인 메서드를 제공한다.

  • mutator method : 원본 배열을 직접 변경하는 메서드
  • accessor method : 원본 배열을 직접 변경하지 않고 새로운 배열을 생성하여 반환하는 메서드

배열 메서드

Array.isArray

전달된 인수가 배열이면 true, 배열이 아니면 false를 반환한다.

Array.prototype.indexOf

배열에 특정 요소가 존재하는지 확인할 때 유용

Array.prototype.push

mutator method

Array.prototype.pop

mutator method

Array.prototype.unshift

mutator method

Array.prototype.shift

mutator method

Array.prototype.concat

accessor method
concat 메서드는 ES6의 스프레드 문법으로 대체할 수 있다.

let result = [1, 2].concat([3, 4]);
console.log(result); // [1, 2, 3, 4]

result = [...[1, 2], ...[3, 4]];
console.log(result); // [1, 2, 3, 4]

Array.prototype.splice

mutator method
배열 중간에 있는 요소를 추가하거나 제거한다.
3개의 매개변수가 있다. (start, deleteCount, items)
배열에서 특정 요소를 제거하려면 indexOf 메서드를 통해 특정 요소의 인덱스를 취득한 다음 splice 메서드를 사용한다.
filter 메서드를 사용하여 특정 요소를 제거할 수도 있지만 특정 요소가 중복된 경우 모두 제거된다.

const arr = [1, 2, 3, 1, 2];
function removeAll(array, item){
    return array.filter(v => v !== item);
}
console.log(removeAll(arr, 2)); // [1, 3, 1]

Array.prototype.slice

accessor method
slice 메서드는 인수로 전달된 범위의 요소들을 복사하여 배열로 변환한다.
두 개의 매개변수를 갖는다. (start, end)
복사본은 얕은 복사를 통해 생성된다.
깊은 복사는 객체에 중첩되어 있는 객체까지 모두 복사하는 것을 말한다. 깊은 복사를 위해서는 Lodash 라이브러리의 cloneDeep 메서드를 사용하는 것을 추천한다.

slice 메서드가 복사본을 생성하는 것을 이용하여 arguments, HTMLCollection, NodeList 같은 유사 배열 객체를 배열로 변환할 수 있다.

Array.prototype.slice.call(arr,0);
Array.from(arr);

function sum(){
    var arr = Array.prototype.slice.call(arguments); // ES5
    // const arr = Array.from(arguments); // ES6
    console.log(arr); // [1, 2, 3];
}
console.log(sum(1,2,3));

arguments 객체는 유사 배열 객체이면서 이터러블 객체다. 이터러블 객체는 ES6의 스프레드 문법을 사용하여 간단하게 배열로 변환할 수 있다.

function sum(){
    const arr = [...arguments];
    console.log(arr); // [1, 2, 3]
}
console.log(sum(1,2,3));

Array.prototype.join

원본 배열의 모든 요소를 문자열로 변환한 후, 인수로 전달받은 문자열로 연결한 문자열을 반환한다.

Array.prototype.reverse

mutator method

Array.prototype.fill

mutator method
ES6에서 도입된 fill 메서드는 인수로 전달받은 값을 배열의 처음부터 끝까지 요소로 채운다.

Array.prototype.includes

indexOf 메서드 대신 ES7에서 도입된 Array.prototype.includes 메서드를 사용하면 가독성이 더 좋다.

Array.prototype.flat

accessor method
ES10에서 도입된 flat 메서드는 인수로 전달한 깊이만큼 재귀적으로 배열을 평탄화 한다.

배열 고차 함수

고차 함수는 함수를 인수로 전달받거나 함수를 반환하는 함수를 말한다.

Array.prototype.sort

mutator method
sort 메서드는 배열의 요소를 정렬한다. 기본적으로 오름차순으로 정렬한다.
숫자 요소를 정렬할 때는 sort 메서드에 정렬 순서를 정의하는 비교 함수를 인수로 전달해야 한다.

const points = [30,20,40,50,3];
points.sort((a, b) => a - b);
console.log(points); // [3, 20, 30, 40, 50]
points.sort((a, b) => b - a);
console.log(points); // [50, 40, 30, 20, 3]

Array.prototype.forEach

accessor method
forEach 메서드는 for문과는 달리 break, continue문을 사용할 수 없다.

[1, 2, 3].forEach((item, index, arr) => {
    console.log(`요소값: ${item}, 인덱스: ${index}, this: ${JSON.stringify(arr)}`);
});
/*
요소값: 1, 인덱스: 0, this: [1, 2, 3]
요소값: 2, 인덱스: 1, this: [1, 2, 3]
요소값: 3, 인덱스: 2, this: [1, 2, 3]
*/

Array.prototype.map

accessor method
map 메서드는 자신을 호출한 배열의 모든 요소를 순회하면서 인수로 전달받은 콜백 함수를 반복 호출한다.
콜백 함수의 반환값들로 구성된 새로운 배열을 반환한다.

const arr = [1, 4, 9].map((item, index, arr) => {
    console.log(`요소값: ${item}, 인덱스: ${index}, this: ${JSON.stringify(arr)}`);
    return Math.sqrt(item);
});
/*
요소값: 1, 인덱스: 0, this: [1, 4, 9]
요소값: 4, 인덱스: 1, this: [1, 4, 9]
요소값: 9, 인덱스: 2, this: [1, 4, 9]
*/
console.log(arr); // [1, 2, 3];

Array.prototype.filter

accessor method
filter 메서드는 자신을 호출한 배열의 모든 요소를 순회하면서 인수로 전달받은 콜백 함수를 반복 호출한다.
콜백 함수의 반환값이 true인 요소로만 구성된 새로운 배열을 반환한다.

const arr = [1, 4, 9].filter((item, index, arr) => {
    console.log(`요소값: ${item}, 인덱스: ${index}, this: ${JSON.stringify(arr)}`);
    return item % 2;
});
/*
요소값: 1, 인덱스: 0, this: [1, 4, 9]
요소값: 4, 인덱스: 1, this: [1, 4, 9]
요소값: 9, 인덱스: 2, this: [1, 4, 9]
*/
console.log(arr); // [1, 9];

Array.prototype.reduce

accessor method
reduce 메서드는 자신을 호출한 배열을 모든 요소를 순회하며 인수로 전달받은 콜백 함수를 반복 호출한다.
콜백 함수의 반환값을 다음 순회 시에 콜백 함수의 첫 번째 인수로 전달하면서 콜백 함수를 호출하여 하나의 결과값을 만들어 반환한다.
reduce 메서드는 첫 번째 인수로 콜백 함수, 두 번째 인수로 초기값을 전달받는다.
reduce 메서드의 콜백 함수에는 4개의 인수가 있다.(초기값 or 콜백함수의 이전반환값, 요소값, 인덱스, this)

const sum = [1,2,3].reduce((init, item, index, array) => {
    return init+item;
},0);
console.log(sum);

Array.prototype.some

some 메서드는 콜백 함수의 반환값이 단 한 번이라도 참이면 true, 모두 거짓이면 false를 반환한다.
즉 결과를 boolean 타입으로 반환한다.

[1,2,3].some((item) => item > 2); // true

Array.prototype.every

every 메서드는 콜백 함수의 반환값이 모두 참이면 true, 단 한 번이라도 거짓이면 false를 반환한다.
즉 결과를 boolean 타입으로 반환한다.

[1,2,3].every((item) => item > 2); // false

Array.prototype.find

인수로 전달된 콜백 함수를 호출하여 반환값이 true인 첫 번째 요소를 반환한다.
(filter 메서드는 배열을 반환한다.)
반환값이 true인 요소가 존재하지 않는다면 undefined를 반환한다.

const users = [
    {id:1, name:'Kim'},
    {id:2, name:'Lee'},
    {id:3, name:'Park'}
]
console.log(users.find(item => item.id === 2)); // {id:2, name:'Lee'}
console.log(users.filter(item => item.id === 2)); // [{id:2, name:'Lee'}]

Array.prototype.findIndex

인수로 전달된 콜백 함수를 호출하여 반환값이 true인 첫 번째 요소의 인덱스를 반환한다.
반환값이 true인 요소가 존재하지 않는다면 -1을 반환한다.

const users = [
    {id:1, name:'Kim'},
    {id:2, name:'Lee'},
    {id:3, name:'Park'}
]
console.log(users.findIndex(item => item.id === 2)); // 1

Array.prototype.flatMap

flatMap 메서드는 map 메서드를 통해 생성된 새로운 배열을 평탄화한다.
즉, map 메서드와 flat 메서드를 순차적으로 실행하는 효과가 있다.
단, flatMap 메서드는 1단계만 평탄화한다. 평탄화 깊이를 지정해야 한다면, map 메서드와 flat 메서드를 각각 호출한다.

const arr = ['hello', 'world'];
arr.map(x => x.split('')).flat();
arr.flatMap(x => x.split(''));