거인의 코딩일지
[JS] Array 의 내장 함수(2) 본문
728x90
Array.prototype.filter()
- Array인스턴스의 filter() 메서드는 주어진 배열의 일부에 대한 얕은 복사본을 생성하고, 주어진 배열에서 제공된 함수에 의해 구현된 테스트를 통과한 요소로만 필터링 합니다.
- ex1) 모든 작은 값 걸러 내기
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// 필터링된 값은 [12, 130, 44]
- ex2) JSON 에서 유효하지 않은 항목 고르기
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" },
];
let invalidEntries = 0;
function filterByID(item) {
if (Number.isFinite(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
const arrByID = arr.filter(filterByID);
console.log("필터링된 배열\n", arrByID);
// 필터링된 배열
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
console.log("유효하지 않은 항목의 수 =", invalidEntries);
// 유효하지 않은 항목의 수 = 5
- ex3) 배열 내용 검색
const fruits = ["apple", "banana", "grapes", "mango", "orange"];
/**
* 검색 조건에 따른 배열 필터링(쿼리)
*/
function filterItems(arr, query) {
return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}
console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
Array.prototype.entries()
- 배열의 각 인덱스에 대한 키/ 값 쌍을 가지는 새로운 ArrayIterator 객체를 반환한다.
- Array.prototype.keys() 와의 차이점은 entries() -> 배열안에 배열처럼 나타나고 key()-> 인덱스로 키를 줄 뿐이다.
Array.prototype.concat()
- 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다.
- 기존 배열을 변경 하지 않고 새로 추가된 배열 을 반환한다.
- ex1) 배열 세개 이어 붙이기
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// 결과는 [1, 2, 3, 4, 5, 6, 7, 8, 9]
- ex2) 배열에 값 이어 붙이기
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// 결과는 ['a', 'b', 'c', 1, 2, 3]
- ex3) 중첩된 배열 사용
const num1 = [[1]];
const num2 = [2, [3]];
const numbers = num1.concat(num2);
console.log(numbers);
// 결과는 [[1], 2, [3]]
// num1의 첫 번째 요소를 수정합니다.
num1[0].push(4);
console.log(numbers);
// 결과는 [[1, 4], 2, [3]]
- ex4) 배열이 아닌 객체에 concat() 연결
console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3]
console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ]
const arrayLike = {
[Symbol.isConcatSpreadable]: true,
length: 2,
0: 1,
1: 2,
2: 99, // length가 2이므로 concat()에서 무시됨
};
console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]
Array.propotype.join()
- 배열의 모든 요소를 연결해 하나의 문자열로 만듬
- Array.protottpe.toString() 와 차이점은 join() 을 사용하면 다양한 구분자를 사용할 수 있고 toString() 를 사용하면 지정된 배열 및 그 요소를 나타내는 문자열을 반환한다.
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// Expected output: "Fire,Air,Water"
console.log(elements.join(''));
// Expected output: "FireAirWater"
console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"
Array.prototype.copyWithin()
- 배열의 일부를 얕게 복사한 뒤 동일한 배열의 위치에 덮어 쓰고 그 배열을 반환 한다.
- 크기(배열의 길이)를 수정하지 않고 반환 한다.
- arr.copyWithin(target [, start [, end] ] )
- target
- 복사한 시퀀스를 넣을 위치를 가리키는 0 기반 인덱스
- 음수를 지정하면 배열에 끝에서부터 계산한다.
- start
- 복사를 시작할 위치를 가리키는 0 기반 인덱스
- 기본값은 0으로 start를 지정하지 않으면 배열의 처음부터 복사
- end
- 복사를 끝낼 위치를 가리키는 0기반 인덱스
- copyWithin 은 end 인덱스 이전까지 복사하므로 end 인덱스 요소는 제외한다.
- 기본값은 arr.length로 end 를 지정하지 않으면 배열 끝까지 복사한다.
- target
const array1 = ['a', 'b', 'c', 'd', 'e'];
// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]
// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]
728x90
'코딩 > JS' 카테고리의 다른 글
[JS] for...in, for...of 의 차이점????? (0) | 2023.10.07 |
---|---|
[J.S] js에서의 프록시(Proxy)! (0) | 2023.10.05 |
[JS] Array 의 내장 함수(1) (0) | 2023.09.26 |
[JS] 객체 환산 연산자란? (...) (0) | 2023.09.25 |
메서드 체인(Method Chaining)이란? (0) | 2023.08.14 |