[배열] 내장함수 ①

TASON·2021년 6월 24일
1

자바스크립트

목록 보기
9/11

배열 내장함수

자바스크립트에서는 배열을 다룰 때 알고 있으면 유용한 다양한 내장 함수가 있다.

forEach map indexof findIndex find filter
splice slice shift unshift pop push includes

이번 포스팅에서는 forEach map indexof findIndex find filter 함수들을 다뤄보도록 하겠다.


forEach

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => {
  console.log(number); // 1 2 3 4 5 출력됨
});

forEach 함수의 매개변수로 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어준다.

이 함수의 매개변수 number는 각 원소를 가르킨다.

이렇게 매개변수에 전달되는 함수를 콜백함수라고 한다.


map

const array = [1, 2, 3, 4, 5];

const square = n => n * n;
const squared = array.map(square);
console.log(squared); // [1, 4, 9, 16, 25] 출력됨

map 함수의 매개변수로 각 원소에 변화를 주는 함수를 전달한다.

이를 변화함수라고 한다.

변화함수를 꼭 변수에 할당해서 쓸 필요는 없다.

const squared = array.map(n => n * n);
console.log(squared); // [1, 4, 9, 16, 25] 출력됨

indexOf

const array = [1, 2, 3, 4, 5];

const index = array.indexOf(3);
console.log(index); // 2 출력됨

indexOf 함수는 매개변수가 배열의 몇번째 원소인지 찾아주는 함수이다.

하지만 배열 내 찾고자하는 매개변수가 존재하지 않는다면 -1을 출력한다.


findIndex

const items = [
  {
    id: 1,
    name: '아메리카노',
    caffeine: true,
  },
  {
    id: 2,
    name: '카페라떼',
    caffeine: true,
  },
  {
    id: 3,
    name: '키위주스',
    caffeine: false,
  },
];

const index = items.findIndex(item => item.caffeine === false);
console.log(index); // 2 출력됨

findIndex는 배열 안에 객체나 배열이 있는 경우 주로 사용된다.

caffeinefalse인 객체를 찾으려면, 콜백함수 조건을 넣어 알맞는 값을 반환하게 한다.

다만 조건에 부합하는 객체나 배열이 여러개이면, 가장 앞에 있는 하나만 반환된다.

find 함수와 마찬가지로 조건에 부합하는 원소가 없다면 -1을 반환한다.


find

const items = [
  {
    id: 1,
    name: '아메리카노',
    caffeine: true,
  },
  {
    id: 2,
    name: '카페라떼',
    caffeine: true,
  },
  {
    id: 3,
    name: '키위주스',
    caffeine: false,
  },
];

const item = items.find(item => item.caffeine === false);
console.log(item); // {id: 3, name: '키위주스', caffeine: false} 출력됨

find 함수는 findIndex 함수와 매우 유사하나 인덱스가 아닌 값 자체를 반환한다.


filter

const items = [
  {
    id: 1,
    name: '아메리카노',
    caffeine: true,
  },
  {
    id: 2,
    name: '카페라떼',
    caffeine: true,
  },
  {
    id: 3,
    name: '키위주스',
    caffeine: false,
  },
];

const caffeineItems = items.filter(item => item.caffeine === true);

filter 함수는 조선을 만족하는 모든 값들을 추출하여 새로운 배열을 반환한다.

이 코드의 결과는 다음과 같이 출력된다.

[
  {
    id: 1,
    name: '아메리카노',
    caffeine: true,
  },
  {
    id: 2,
    name: '카페라떼',
    caffeine: true,
  },
]
profile
프론트엔드 개발자 / iOS 개발 스터디 중

0개의 댓글