Javascript-14 (forEach, map, filter, reduce)

Patrick·2021년 4월 20일
0

Javascript

목록 보기
14/18
post-thumbnail

오늘은 Javascript는 물론 React에서도 자주 사용하게 되는 몇 API에 대해서 정리를 해보려고 한다.
React를 사용하다보면 유독 자주 사용하게 되는 몇몇이 있는데 오늘 정리할 이 API들만 조금 알아도 도움이 된다.

forEach

  • 반복문을 돌려주는 것!
const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

이런 배열이 있다고 해보자!

만약 animals 각각에 대해서 알고 싶다면? 혹은 animal 중에서도 size만 따로 빼서 다 보고 싶다면?
이런 경우 forEach를 사용해주면 된다를 사용해주면 된다

animals.forEach((animal) => {
  console.log(animal);
})

animals.forEach((animal) => {
  console.log(animal.size);
})

이렇게 해주면 원하는 것들을 반복문을 돌면서 다 나타나게 할 수 있다.

두 번째 인자도 있는데, 이는 반복문의 인덱스를 나타낸다

animals.forEach((animal, index) => {
  console.log(index, animal.name);
})

0 "lion"
1 "monkey"
2 "rat"

이런 결과가 나온다


map

  • 어떤 배열을 다른 형태의 배열로 재생산 할 때 사용하는 반복문
  • 배열 안의 요소 하나하나를 다른 것으로 변환해준다
const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

// 변수를 만들어서 사용해보자!
const animalsNames = animals.map((animal)=> {
  return animal.name;
})

console.log(animalsNames); 

const animalsSize = animals.map((item)=> {
  return `Animal's size is ${item.size}`;
})

console.log(animalsSize);

이는 다른 형태의 배열을 재생산 하므로 console.log 또한 배열로 나타난다

filter

  • 원하는 데이터만 걸러서 새로운배열을 전달해줄 때!
const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

const smallAnimals = animals.filter((item) => {
  return item.size === 'medium';
})

console.log(smallAnimals);

데이터를 뽑는 것 뿐 아니라 !=(같지 않다)를 사용하면 그것만 빼는 것도 가능하다.

const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

const smallAnimals = animals.filter((item) => {
  return item.size !== 'medium';
})

console.log(smallAnimals);

(예전에 쇼핑몰 만들 때 물건을 빼는 형태에서 사용해봤다)

reduce

  • 배열 안에 있는 값들의 합을 구할 때 사용 된다.
  • 값이 current에 먼저 전달되고, return 한 값이 acc로 전달 되어 누적된다.
const numbers = [1, 10, 11, 23, 444];

// acc : accumulate(더해진 현재 값), current(현재 값)
const total = numbers.reduce((acc, cur) => {
  console.log(acc, cur)
  return acc+cur;
})

console.log(total); // 489

[ reduce 예제 ]

Q : 학생들 socre를 다 더해서 평균 값을 구해라

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}

const students = [
  new Student("A", 29, true, 45),
  new Student("B", 28, false, 80),
  new Student("C", 30, true, 90),
  new Student("D", 40, false, 66),
  new Student("E", 18, true, 88)
];

{
  const result = students.reduce((prev, cur) => {
    return prev + cur.score; // 총 더한 값
  }, 0);
  console.log(result / stduents.length); // 길이를 나눠주면 평균 값!
}
profile
예술을 사랑하는 개발자

0개의 댓글