JavaScript(ES6) | forEach, Map, Filter, reduce (배열 반복)

Ryan·2020년 8월 16일
0

ES6

목록 보기
5/5
post-thumbnail

Iterater는 배열의 모든 엘리먼트에 접근하고 조작할 수 있는 방법이다.

1. Array Iterater Mathod

1) .forEach()

: 배열 속 모든 엘리먼트에 콜백 함수로부터 인수를 받아 동일한 코드를 실행시켜주는 메서드다.

function printGrocery(element){
  console.log(element);
}
groceries.forEach(printGrocery);
  • Return : undifind를 반환한다.
  • 형태 : 배열이름 + .forEach + (익명의 콜백 함수)
const groceries = ['1','2','4','5']
groceries.forEach(groceryEle => console.log(groceryEle));
  • 화살표 함수를 사용하여 표현하면 위와 같다.

2) .map()

: 두번째는 map이다. map은 새로운 배열을 반환한다.

const numbers = [1, 2, 3, 4, 5]; 
const bigNumbers = numbers.map(element => {
  return element * 10;
});

console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]
  • Return : 새로운 배열
const bigNums = [1, 2, 3, 4, 5].map(el => el * 5);
  • 위와 같이 표현할 수도 있다.

3) .filter()

: 세번째는 filter이다. 우리가 원하는 엘리먼트만 골라서 새로운 배열에 넣어줄 것이다.
콜백 함수에 전달된 요소가 True인 엘리먼트만 새로운 배열에 추가된다.

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 
const shortWords = words.filter(word => {
  return word.length < 6;
});

console.log(words); // Output: ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 
console.log(shortWords); // Output: ['chair', 'music', 'brick', 'pen', 'door']
  • Return : 새로운 배열
  • 따라서 조건에 맞는(6보다 작은) 엘리먼트만 shortWords에 추가된다.

4) .findIndex()

: 네번째는 findIndex이다. 말그대로 위치를 찾아주는 메서드다.
콜백 함수에서 True가 되는 엘리먼트의 첫번째 인덱스를 반환해준다.

const jumbledNums = [123, 25, 78, 5, 9]; 
const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

console.log(lessThanTen); // Output: 3 
  • Return : Index 값
  • 10보다 작은 첫번째 엘리먼트는 5다. 따라서 5의 인덱스값 3이 반환된다.
  • 만약 조건을 만족시키는 엘리먼트가 한개도 없을 경우 -1을 반환한다.

5) .reduce()

: 누적된 값을 반환시키는 메서드이다.

  • Return : 최종 누적된 값
  • 형태 : arr.reduce(callback, 최초값)

(1) Callback

: 누산기 (accumulator) : 콜백의 반환값을 누적, 이전 반복에서의 리턴 값
: 현재 값 (currentValue) : 현재 엘리먼트 값
: 현재 인덱스 (currentIndex) : 현재 엘리먼트의 인덱스

(2) initialValue)

: callback의 최초 호출에서 첫 번째 인수에 제공하는 값.

const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
})

console.log(summedNums) // Output: 17
profile
"꾸준한 삽질과 우연한 성공"

0개의 댓글