-
[JS] 자주 사용하는 배열 내장 함수Javascript 2023. 4. 20. 17:19

▶ Array.prototype.concat()
- 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // Expected output: Array ["a", "b", "c", "d", "e", "f"]▶ Array.prototype.entries()
- 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환
const array = ["a", "b", "c"]; const arrayEntries = array.entries(); for (const element of arrayEntries) { console.log(element); } // [0, 'a'] // [1, 'b'] // [2, 'c']▶ Array.prototype.find()
- 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다.
- 그런 요소가 없다면 undefined를 반환
const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // Expected output: 12▶ Array.prototype.filter()
- 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // Expected output: Array ["exuberant", "destruction", "present"]▶ Array.prototype.forEach()
- 주어진 함수를 배열 요소 각각에 대해 실행
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // Expected output: "a" // Expected output: "b" // Expected output: "c"▶ Array.prototype.includes()
- 배열에 어떤 값이 존재하는지 검사
- boolean으로 반환(직관적)
const array1 = [1, 2, 3]; console.log(array1.includes(2)); // Expected output: true const pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // Expected output: true console.log(pets.includes('at')); // Expected output: false▶ Array.prototype.indexOf()
- 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // Expected output: 1 // Start from index 2 console.log(beasts.indexOf('bison', 2)); // Expected output: 4 console.log(beasts.indexOf('giraffe')); // Expected output: -1▶ Array.prototype.keys()
- 배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환
const array1 = ['a', 'b', 'c']; const iterator = array1.keys(); for (const key of iterator) { console.log(key); } // Expected output: 0 // Expected output: 1 // Expected output: 2▶ Array.prototype.map()
- 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환
var numbers = [1, 4, 9]; var doubles = numbers.map(function(num) { return num * 2; }); // doubles는 이제 [2, 8, 18] // numbers는 그대로 [1, 4, 9]▶ Array.prototype.pop()
- 배열에서 마지막 요소를 제거하고 그 요소를 반환
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // Expected output: "tomato" console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage"]▶ Array.prototype.push()
- 배열에서 마지막 요소를 제거하고 그 요소를 반환
const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count); // Expected output: 4 console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push('chickens', 'cats', 'dogs'); console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]▶ Array.prototype.shift()
- 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환
const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1); // Expected output: Array [2, 3] console.log(firstElement); // Expected output: 1▶ Array.prototype.unshift()
- 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환
arr.unshift([배열 맨 앞에 추가할 요소])const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // Expected output: 5 console.log(array1); // Expected output: Array [4, 5, 1, 2, 3]▶ Array.prototype.reduce()
- 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환
- 누산기
const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (accumulator, currentValue) => accumulator + currentValue, initialValue ); console.log(sumWithInitial); // Expected output: 10▶ Array.prototype.sort()
- 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환
- 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따른다.
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // Expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // Expected output: Array [1, 100000, 21, 30, 4]숫자 정렬에서는 4가 30보다 앞에 오지만 숫자는 문자열로 변환되기 때문에 "30"은 유니 코드 순서에서 "4" 앞에 온다.
문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있다. 다음 함수는 배열을 오름차순으로 정렬한다.
var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]▶ Array.prototype.reverse()
- 배열의 순서를 반전
- 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 된다.
const array1 = ['one', 'two', 'three']; const reversed = array1.reverse(); console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"]▶ Array.prototype.splice()
- 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // Inserts at index 1 console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // Replaces 1 element at index 4 console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "May"]▶ Array.prototype.toString()
- 지정된 배열 및 그 요소를 나타내는 문자열을 반환
arr.toString()const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // Expected output: "1,2,a,1a"'Javascript' 카테고리의 다른 글
[JS] 즉시 실행 함수 표현(IIFE, Immediately Invoked Function Expression) (0) 2023.04.20 [JS] 호이스팅(hoisting) (0) 2023.04.20 [JS] 객체(Object) [생성/프로퍼티/인스턴스] (0) 2023.04.20 [JS] 나머지 매개변수(rest parameter) (0) 2023.04.19 [JS] 마우스 움직임을 추적하여 커서를 바꿔보자 (0) 2023.03.27