array.filter()
주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다.
let numbers = [9, 5, 14, 3, 11];
let numbersAboveTen = numbers.filter(function(number) {
return number > 10;
});
console.log(numbersAboveTen); // [14, 11]
array.find()
주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다. 그런 요소가 없다면 undefined를 반환한다.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
array.findIndex()
주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환한다. 만족하는 요소가 없으면 -1을 반환한다.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element >13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
find()와 findIndex()메소드의 차이점
1. find()는 값을 반환한다면 findIndex()는 인덱스를 반환한다.
filter()와 find()메소드의 차이점
1. filter()는 항상 배열을 반환한다.
(조건이 일치하지 않아도 빈 배열로 반환한다)
2. find()는 콜백 함수와 일치하는 첫번째 요소의 값을 반환한다.(조건이 일치하지 않으면 undifined를 반환한다)
eg) 조건을 충족하는 항목이 없는 예제
let numbers = [9, 5, 14, 3, 11];
// filter() ALWAYS returns an array (even if it's empty)
numbers.filter(function(number) {
return number >= 15;
}); // []
// .find() returns the first match or undefined (when none of the items satisfy the condition)
numbers.find(function(number) {
return number >= 15;
}); // undefined