Javascript Array Method 모음
pop
• 배열에서 마지막 요소를 제거하고 그 요소를 반환 • 빈 배열일 경우 undefined를 반환 ❗ |
const array = [1, 2, 3, 4];
console.log(array.pop()); // 4
console.log(array); // [1, 2, 3]
push
• 배열의 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환 • 매개변수 : 배열 끝에 추가할 요소들 |
const array = ["apple", "banana"];
console.log(array.push("mango")); // 3
console.log(array) // ["apple", "banana", mango"];
sort
• 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환 • 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따름❗ • 매개변수 : 정렬 순서를 정의하는 함수 |
const months = ['March', 'Jan', 'Feb', 'Dec'];
console.log(months.sort()); // ["Dec", "Feb", "Jan", "March"]
const array = [1, 30, 4, 21, 100000];
console.log(array.sort((a, b) => a - b)); // 오름차순 정렬 : [1, 4, 21, 30, 100000]
console.log(array.sort((a, b) => b - a)); // 내림차순 정렬 : [100000, 30, 21, 4, 1]
shift
• 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환 • 빈 배열일 경우 undefined를 반환 ❗ |
const array = [1, 2, 3, 4];
console.log(array.shift()); // 1
console.log(array); // [2, 3, 4]
unshift
• 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환 • 매개변수 : 배열 맨 앞에 추가할 요소들 |
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 5
console.log(array1); //[4, 5, 1, 2, 3]
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"
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']
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]
slice
• 배열의 추출 시작점(begin)부터 추출을 종료 할 인덱스(end 미포함)까지 새로운 배열을 반환 • begin이 음수일 경우 배열의 끝에서부터 시작 - undefined인 경우 0번 인덱스부터 시작 - 배열 길이보다 크면 빈 배열 반환 • end가 음수일 경우 배열의 끝에서부터의 길이를 나타냄 - end가 생략되거나 길이보다 크면 배열(arr.length)끝까지 추출 |
array.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"]
console.log(animals.slice()); // ["ant", "bison", "camel", "duck", "elephant"]
splice, slice 차이점 🔥
splice와 slice는 공통적으로 배열의 특정한 부분을 return한다.
• splice는 기존 요소를 삭제뿐만 아니라 교체, 추가가 가능하고 원본 배열을 변경시킨다(파괴적 처리).
• slice는 특정한 부분(교체, 추가 불가능)만 반환 하지만 원본 배열을 변경시키지 않는다(비파괴적 처리).
만약 원본 배열을 변경 시키지 않고 요소를 교체, 추가하고 싶다면
1. slice 후 splice
// 첫 번째 방법 : slice한 값을 새로운 변수에 담고 그 후에 splice
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
const array = animals.slice() // 원본 배열을 slice 하고 array에 선언
array.splice(1, 0, "hello") // 그 후 splice
console.log(animals)
// 원본 배열 : ['ant', 'bison', 'camel', 'duck', 'elephant']
console.log(array)
// 변경 배열 : ['ant', 'hello', 'bison', 'camel', 'duck', 'elephant']
2. Spread Operator(ES6)
// 두 번째 방법 : Spread Operator를 사용하여 복사 후 splice
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
const array = [...animals];
array.splice(1, 0, "hello");
console.log(animals);
// 원본 배열 : ['ant', 'bison', 'camel', 'duck', 'elephant']
console.log(array);
// 변경 배열 : ['ant', 'hello', 'bison', 'camel', 'duck', 'elephant']
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"]
forEach
• 배열 요소 각각에 대해 주어진 함수(callback)를 실행 • callback은 세 인수와 함께 호출됨 - currentValue (처리할 현재 요소) - index (처리할 현재 요소의 인덱스) - array (forEach()를 호출한 배열) |
array.forEach(callback(currentvalue[, index[, array]])[, thisArg])
const array = ["a", "b", "c"];
array.forEach((value, idx) => {
console.log(value, idx);
})
/*
a 0
b 1
c 2
*/
map ✨
• 배열 요소 각각에 대해 주어진 함수(callback)를 호출한 결과를 모아 새로운 배열을 반환 • callback은 세 인수와 함께 호출됨 - currentValue (처리할 현재 요소) - index (처리할 현재 요소의 인덱스) - array (map()을 호출한 배열) |
arr.map(callback(currentValue[, index[, array]])[, thisArg])
const array1 = [1, 2, 3, 4, 5];
// 각 요소에 2를 곱해서 array2에 return하는 함수
const array2 = array1.map(value => {
return value * 2
})
console.log(array2) // [2, 4, 6, 8, 10]
filter ✨
• 배열에 주어진 함수의 테스트 통과하는 모든 요소를 모아 새로운 배열로 반환 • callback은 세 인수와 함께 호출됨 - currentValue (처리할 현재 요소) - index (처리할 현재 요소의 인덱스) - array (filter()를 호출한 배열) |
arr.filter(callback(element[, index[, array]])[, thisArg])
const array1 = ["유재석", "김종민", "김범수", "강호동", "김희철"];
const array2 = array1.filter(value => {
// 문자열 앞(index 0)이 김씨인 사람만 return
return value.charAt(0) === "김"
})
console.log(array2); // ['김종민', '김범수', '김희철']
reduce ✨
• 배열의 각 요소에 대해 주어진 리듀서(reducer)함수를 실행하고, 하나의 결과값을 반환 • callback은 네 가지 인수와 함께 호출됨 - accumulator(누산기) → 콜백의 반환값을 누적 (initialValue를 제공한 한 경우 initialValue 값) - currentValue(현재 값) → 처리할 현재 요소 - currentIndex(현재 인덱스) → 처리할 현재 요소 인덱스 (initialValue를 제공한 경우 index 0, 아니면 index 1부터 시작) - array(원본 배열) → reduce()를 호출한 배열 |
arr.reduce(callback[, initialValue])
// arr.reduce(콜백함수(누산기, 현재 값, 현재 인덱스, 원본 배열) => {}, 초기 값)
const array = [1, 2, 3, 4, 5];
const sum = array.reduce((acc, cur) => {
console.log(`acc : ${acc} cur : ${cur}`);
return acc + cur
})
/*
acc : 1 cur : 2
acc : 3 cur : 3
acc : 6 cur : 4
acc : 10 cur : 5
*/
console.log(sum); // 15