Modern JavaScript #8 배열 내장함수

이말감·2021년 8월 5일
0

JavaScript

목록 보기
8/13

forEach

: 가장 쉬운 배열 내장함수
기존에 우리가 배웠던 for문을 대체 시킬 수 있다.

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

// for문을 사용한 경우
for (let i=0; i<superheroes.length; i++ ) {
  console.log(superheroes[i]);
}

// for .. of를 사용한 경우
for (let hero of superheroes) {
  console.log(hero);
}

// forEach를 사용한 경우
superheroes.forEach(hero => {
  console.log(hero);
})

forEach 함수의 파라미터로는 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어준다.
이 함수의 파라미터 hero는 각 원소를 가리키게 된다.
이렇게 함수 형태의 파라미터를 전달하는 것을 콜백함수라고 부른다.
함수를 등록해주면 forEach가 실행을 해준다.

map

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

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

//for 문 사용
for (let i=0; i<array.length ; i++) {
  squared.push(array[i]*array[i]);
}
console.log(squared);

//forEach 사용
const squared2 = [];
array.forEach(num => {
  squared2.push(num*num)
})

console.log(squared2);

//map 사용
const square = n => n*n;
const squared3 = array.map(square);
console.log(squared3);

map 함수의 파라미터로는 변화를 주는 함수를 전달해준다.
변화를 주는 함수인 square는 n을 받아와서 이를 제곱해준다.
array.map 함수를 사용할 때 square를 변화를 주는 함수로 사용함으로서, 내부의 모든 값에 대하여 제곱을 해서 새로운 배열을 생성하였다.

const squared = array.map(n=>n*n);

으로 코드를 작성해도 된다.

indexOf

: 원하는 항목이 몇 번째 원소인지 찾아주는 함수.

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

console.log(superheroes.indexOf('토르'));

findIndex

: 배열 안에 있는 값이 숫자, 문자열, 또는 Boolean일 때 찾고자하는 항목이 몇 번째 원소인지 알아내려면 indexOf를 사용하면 된다. 하지만 배열 안에 있는 값이 객체이거나, 배열이라면 indexOf로 찾을 수 없다.

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

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);

todos라는 배열이 객체가 들어있을 때, 어떤 객체의 id가 3일 때 그 객체가 몇 번째 원소인지를 findIndex를 이용해서 찾을 수 있다.

todos.findIndex(todo => todo.id === 3)

todos 안의 객체 하나하나가 todo일 때 todo의 id가 3인 인덱스를 찾으라는 말이다.

find

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

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

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

즉 todos라는 배열 안에 객체로 이루어져 있으므로 find를 사용하면 객체 값을 받을 수 있다는 것이다.

filter

: 배열에서 특정 조건을 만족하는 값들만 따로 추출하여 새로운 배열을 만든다.
예를 들어 todos 배열에서 done 값이 false인 항목들만 따로 추출해서 새로운 배열을 만들어보자.

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

const fil = todos.filter(todo => todo.done === false);
console.log(fil);
const fil = todos.filter(todo => todo.done === false);

todo라는 객체에서 done이 false 일 때 filter를 통해 fil이라는 새로운 배열을 만드는 것이다.
예시가 true, false를 반환하기 때문에 아래와 같이 입력할 수 있다.

const tasksNotDone = todos.filter(todo => !todo.done);

splice

: 배열에서 특정 항목을 제거할 때 사용한다.

const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);
numbers.splice(index, 1);
console.log(numbers);

특정 항목의 인덱스 값을 알아낸 뒤 splice로 제거할 수 있다.

배열.splice(index값, [index로부터 몇 개를 지울 것인지 개수])

splice를 사용할 때 첫 번째 파라미터는 어떤 인덱스부터 지울지를 의미하고 두 번째 파라미터는 그 인덱스로부터 몇 개를 지울지를 의미한다.

slice

: splice와 비슷하다. 배열을 잘라낼 때 사용하는데, 중요한 점은 기존의 배열을 건들지 않고 새로운 배열을 만드는 것이다.

const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0,2);

console.log(numbers);
console.log(sliced);

splice에는 두 개의 파라미터를 넣게 되는데
첫 번째 파라미터는 어디서부터 자를지, 두 번째 파라미터는 어디까지 자를지 의미한다.
numbers.slice(0,2) 이므로 0부터 2전까지 자른다는 의미이다.

shift, pop

  • shift
    : 첫 번째 원소를 배열에서 추출해준다. 추출하는 과정에서 배열의 해당 원소는 사라진다.
const numbers = [10, 20, 30, 40];
const value = numbers.shift();
console.log(value);
console.log(numbers);

//10
//[20,30,40]
  • pop
    : 마지막 원소를 배열에서 추출한다. shift와 마찬가지로 배열의 해당 원소는 사라진다.
const numbers = [10, 20, 30, 40];
const value = numbers.pop();
console.log(value);
console.log(numbers);

//40
//[10,20,30]

pop은 push의 반대이다. push는 배열의 맨 마지막에 새 항목을 추가하고 pop은 맨 마지막 항목을 추출한다. 스택에서 사용된다고 생각하면 된다.
push-pop : 스택, push-shift : 큐

unshift

: unshift는 shift의 반대. 배열의 맨 앞에 새 원소를 추가한다.

const numbers = [10, 20, 30, 40];
numbers.unshift(5);
console.log(numbers);
// [
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]

concat 함수는 arr1과 arr2에 변화를 주지 않고 새로운 배열을 만든다.
여러 개의 배열을 합칠 경우 concat() 안에 합치고 싶은 순서대로 배열명을 쓰면 된다.

join

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

const array = [1,2,3,4,5,6]
console.log(array.join());
console.log(array.join(' '));
console.log(array.join(', '));
//1,2,3,4,5,6
//1 2 3 4 5 6
//1, 2, 3, 4, 5, 6

join에 ' '나 ', '처럼 추가한다면 배열 안의 값들이 문자열 형태로 합쳐질 때 입력된 값으로 나눠서 합쳐진다.

reduce

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

//forEach로 배열 합 구하기
let sum = 0;
array.forEach(num => {
  sum+= num;
})

console.log(sum);

// reduce로 배열 합 구하기
let sum2 = array.reduce((accumulator, current) => accumulator + current,0);
console.log(sum2);

(* reduce와 map 참고)

//forEach
function countBiggerThanTen(numbers) {
  let big = 0;
  numbers.forEach(num => {
    if (num > 10){
      big+=1;
    }
  })
  return big;
}

// map
function countBiggerThanTen(numbers) {
  let big = 0;
  const sik = num => {
    if(num > 10) {
      big += 1;
    }
  }
  numbers.map(sik);
  return big;
}

//reduce 
function countBiggerThanTen(numbers) {
  let num = numbers.reduce((acc, curr) => curr > 10 ? acc+1 : 0,0);
  return num;
}


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

위 코드를 작성할 때 reduce는 이 블로그를 보고 조금 감을 잡았다.

array.reduce(callback(accumulator, currentValue\[, index\[, array]] )\[, initialValue])

참고

array.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue])

  • accumulator : 반환값이 누적되는 곳.
  • currentValue : array에서 받아온 현재 값
  • index : 현재 처리되고 있는 값의 인덱스
  • array : 현재 호출된 배열

array.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue])

  • initialValue : accumulator의 초기값

이때 initialValue가 없을 경우 배열의 첫번째 인자가 accumulator가 되기 때문에 두번째 인자가 currentValue가 된다.

profile
전 척척학사지만 말하는 감자에요

0개의 댓글