배열 내장함수 : 배열을 다룰 때 유용한 내장 함수

forEach

우선 for문을 사용하면

const  superHeroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지']

for (let i = 0; i < superHeroes.length; i++){
  console.log(superHeroes[i]);
}

forEach 함수를 사용하면

const  superHeroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지']

superHeroes.forEach(hero => {
  console.log(hero);
})

forEach 함수의 파라미터로는, 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어줍니다. 이 함수의 파라미터 hero는 각 원소를 가르키게 됩니다.

이렇게 함수형태의 파라미터를 전달하는 것을 콜백함수 라고 부릅니다. 함수를 등록해주면, forEach 가 실행을 해주는 거죠.

map

map 은 배열 안의 각 원소를 변환 할 때 사용 되며, 이 과정에서 새로운 배열이 만들어집니다.

forEach 함수로 구현

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

const squared = [];

array.forEach(n => {
  squared.push(n * n);
});

console.log(squared);

map 함수로 구현

const array = [1, 2, 3, 4, 5, 6, 7, 8]

const squared = array.map(n => n * n);
console.log(squared);
찍히는 값 = [1, 4, 9, 16, 25, 36, 49, 64]

다른 예시,

const items = [
  {
    id: 1,
    text: 'hello'
  },
  {
    id: 2,
    text: 'world'
  }
]
const texts = items.map(item => item.text);
console.log(texts);
찍히는 값 = ["hello", "world"]

indexOf

indexOf 는 원하는 항목이 배열의 몇번째 원소인지 찾아주는 함수입니다.

const superHeroes2 = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스터레인지'];
const index = superHeroes2.indexOf('토르');
console.log(index);
찍히는 값 = 2

findIndex

배열 안에 있는 값이 객체이거나, 배열이라면 indexOf 로 찾을 수 없습니다.

const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true,
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true,
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true,
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
]

const index2 = todos.findIndex(todo => todo.id === 3);
console.log(index2);
찍히는 값 = 2

find

find 함수는 findIndex 랑 비슷한데, 찾아낸 값이 몇번째인지 알아내는 것이 아니라, 찾아낸 값 자체를 반환합니다.

const todo = todos.find(todo => todo.id === 3);
console.log(todo);
찍히는 값 = {id: 3, text: "객체와 배열 배우기", done: true}

filter

filter 함수는 배열에서 특정 조건을 만족하는 값들만 따로 추출하여 새로운 배열을 만듭니다.

const tasksNotDone = todos.filter(todo => !todo.done);
console.log(tasksNotDone);
찍히는 값 = [{id: 4, text: '배열 내장함수 배우기', done: false}]

splice

특정 항목을 제거할 때 사용합니다.

const numbers = [10, 20, 30, 40];
const index3 = numbers.indexOf(30);
const spliced = numbers.splice(index3, 1);
console.log(spliced);
찍히는 값 = 30
console.log(numbers);
찍히는 값 = [10, 20, 40]

numbers.splice(index3, 1);
splice 를 사용 할 때 첫번째 파라미터(index3)는 어떤 인덱스부터 지울지를 의미하고 두번째 파라미터(1)는 그 인덱스부터 몇개를 지울지를 의미합니다.

slice

slice 는 splice처럼 배열을 잘라낼 때 사용하는데, 중요한 점은 기존의 배열은 건들이지 않는다는 것입니다.

const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2); 
// 0부터 시작해서 2전까지
   10부터 ~~~~~ 30전까지

const sliced = numbers.slice(0, 2);
console.log(sliced);
찍히는 값 = [10, 20]
console.log(numbers);
찍히는 값 = [10, 20, 30, 40]
기존의 배열 변화 없음!

shift, pop

shift 는 첫번째 원소를 배열에서 추출해줍니다. (추출하는 과정에서 배열에서 해당 원소는 사라집니다.)

const numbers = [10, 20, 30, 40];

const value = numbers.shift();
console.log(value);
찍히는 값 = [10]
console.log(numbers);
찍히는 값 = [20, 30, 40]

pop : 마지막 원소를 배열에서 추출

const numbers2 = [10, 20, 30, 40];
const values = numbers2.pop();
console.log(values);
찍히는 값 = [40]
console.log(numbers2);
찍히는 값 = [10, 20, 30]

pop 은 push 의 반대로 생각하시면 됩니다. push 는 배열의 맨 마지막에 새 항목을 추가하고, pop 맨 마지막 항목을 추출합니다.

unshift

unshift 는 shift 의 반대입니다.
배열의 맨 앞새 원소를 추가합니다.

const numbers3 = [10, 20, 30, 40];

numbers3.unshift(5);
console.log(numbers3)
찍히는 값 = [5, 10, 20, 30, 40]

concat

여러개의 배열을 하나의 배열로 합쳐줍니다.
기존의 배열을 건드리지 않음

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6]

const concated = arr1.concat(arr2);
console.log(concated);
찍히는 값 = [1, 2, 3, 4, 5, 6];

join

배열 안의 값들을 문자열 형태로 합쳐줍니다.

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

console.log(array.join());
찍히는 값 = 1,2,3,4,5

console.log(array.join(' '));
// 문자열 사이에 공백을 넣어줌
찍히는 값 = 1 2 3 4 5

console.log(array.join(', '));
찍히는 값 = 1, 2, 3, 4, 5
// 문자열 사이에 공백과 콤마를 넣어줌

reduce

배열 연산할 때 사용하는 내장함수입니다.

배열에 있는 각 원소들을 다 더하기

먼저 forEach 함수를 사용하면

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

let sum = 0;
numbers.forEach(n => {
  sum += n;
})
console.log(sum);

const sum2 = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum2);

reduce 함수에는 두개의 파라미터를 전달합니다. 첫번째 파라미터는 accumulator와 current를 파라미터로 가져와서 결과를 반환하는 콜백함수이구요, 두번째 파라미터는 reduce 함수에서 사용 할 초깃값입니다.

여기서 accumulator 는 누적된 값을 의미합니다.

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

const sum2 = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum2);
찍히는 값 = 15

총 원소들의 평균값 구하기

const avg = numbers.reduce((accumulator, current, index, array) => {
  if(index === array.length - 1){
  // 배열은 0부터 시작이니까 
    return(accumulator + current) / 
    array.length;
    // 15/5 = 3
  }
  return accumulator + current;
}, 0);
console.log(avg);
찍히는 값 = 3

위 코드의 reduce 에서 사용한 콜백함수에서는 추가 파라미터로 index 와 array 를 받아왔습니다. index 는 현재 처리하고 있는 항목이 몇번째인지 가르키고, array 는 현재 처리하고 있는 배열 자신을 의미합니다.

배열 안 원소의 해당 갯수 구하기

const alphabets = ['a', 'a', 'a', 'b', 'c', 'c', 'c', 'e'];
const counts = alphabets.reduce((acc,current) => {
  if(acc[current]){
    acc[current] += 1;
  }else{
    acc[current] = 1;
  }
  return acc;
}, {})

console.log(counts);

퀴즈
forEach를 사용하면

function countBiggerThanTen(numbers){
    let count = 0;
    numbers.forEach(n => {
      if(n > 10){
        count++;
      }
    });
    return count
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5

reduce를 사용하면

function countBiggerThanTen(numbers){
    return numbers.reduce((acc, current) => {
        if (current > 10) {
          return acc + 1;
        } else {
          return acc;
        }
    }, 0);
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5

filter를 사용하면 코드가 제일 짧아진다.

function countBiggerThanTen(numbers){
	return numbers.filter(n => n > 10).length;
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5

study by. 벨로퍼트와 함께하는 모던 자바스크립트

profile
백엔드와 프론트엔드를 사랑하는 현 마크업개발자(퍼블리셔)입니다 :) 자바스크립트, React, Python을 공부하고 있습니다.

2개의 댓글

comment-user-thumbnail
2020년 4월 23일

정리 깔끔하네요 👍

1개의 답글