JS - array 메소드 정리(2)

지송현·2022년 9월 27일
0

JS

목록 보기
6/9
post-thumbnail

이전 글에 이어 자바스크립트 배열 메소드를 정리해보자.

1. find

주어진 배열에서 조건을 만족하는 첫번째 요소를 찾는 메소드이다. 구조는 아래와 같다.

arr.find(callback[, thisArg])
  • 예시)
var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

  • 예시2) 화살표 함수 사용
const inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

const result = inventory.find(fruit => fruit.name === 'cherries');

console.log(result) // { name: 'cherries', quantity: 5 }


2. filter

주어진 함수의 조건을 만족하는 모든 요소를 모아 새로운 배열로 반환한다. 구조는 아래와 같다.(콜백 함수의 리턴값이 true인 요소를 모은다.)

arr.filter(callback(element[, index[, array]])[, thisArg])
  • 예시)
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"]


3. map

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다. 구조는 다음과 같다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])
  • 예시)
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

filter와 map이 아주 유사해 보인다.
일단 filter에는 조건을 넣고, map에는 실행 동작을 넣는 것으로 하자.

profile
백엔드 개발자

0개의 댓글