.filter .map .reduce .every

zitto·2023년 3월 26일
0

Study

목록 보기
1/2
post-thumbnail

지난 알고리즘 수업 때 멘토님께서 알려주셨듯이
실무에서는 for문은 잘 사용하지 않는다고 하셨다.
그렇다면 for문 말고도 배열에서 사용할 수 있는 함수는 어떤 것들이 있을까?

배열의 내장함수로 filter와 map이 있다.
먼저, filter에 대해 알아보자!

💡.filter()

✅ filter

filter 는 걸러주는 함수로,
요소를 걸러내어 배열로 true/false 반환, 없으면 빈 배열

  • [구문 형태]
arr.filter(callback(element[, index[, array]])[, thisArg])

callback : 각 요소를 시험할 함수
element : 처리할 현재 요소
index(Optional) : 처리할 현재 요소의 인덱스.
array(Optional) : filter를 호출한 배열.
thisArg(Optional) : callback을 실행할 때 this로 사용하는 값.

  • [예시]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
const guys = [
    { name: 'YD', money: 500000 },
    { name: 'Bill', money: 400000 },
    { name: 'Andy', money: 300000 },
    { name: 'Roky', money: 200000 }
];
const rich = guys.filter(man => man.money > 300000);
console.log(rich);
// [{name: "YD", money: 500000}]

-> filter는 원시적인 값만 사용할 수 있는게 아니라,
JSON과 같은 객체를 사용해 true 판별이 가능하다.

filter는 filtter자체만으로도 쓰임이 좋지만 다른 함수와의 조합성도 좋아 map,reduce같은 다른 함수들과 함께 자주 쓰인다.

  • [예시]
const guys = [
    { name: 'YD', money: 500000 },
    { name: 'Bill', money: 400000 },
    { name: 'Andy', money: 300000 },
    { name: 'Roky', money: 200000 }
];
const richNames = guys.filter(man => man.money > 300000)
    .map(man => man.name)
console.log(richNames);
// ["YD", "Bill"]

따라서 filter는 조합을 이용해 사용하는 경우 강력한 힘을 발휘한다!

✅ filter 사용 시 주의 사항

  1. 원본 배열은 변하지 않는다.
  2. 문자열에서는 사용이 불가능하다.
  3. 값이 존재하지 않는 배열은 filter함수가 실행되지 않는다.
  4. 값이 비어있는 인덱스 또한 호출되지 않는다.
  5. 함수가 실행된 이후(filter 사용 이후의 줄)에서 기존 배열에 값을 추가해도
    filter는 반영되지 않는다.

💡.map()

배열을 순회하며 요소마다 callback 함수 적용 후 새로운 배열로 리턴한다.
map은 callback 함수를 각각의 요소에 대해 한번씩 순서대로 불러 그 함수의 반환값으로 새로운 배열을 만든다.
callback 함수는 (undefined도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출된다.

  • [구문 형태]
arr.map(callback(currentValue[, index[, array]])[, thisArg])

callback : 새로운 배열요소를 생성할 함수
element : 처리할 현재 요소
index(Optional) : 처리할 현재 요소의 인덱스.
array(Optional) : map을 호출한 배열.
thisArg(Optional) : callback을 실행할 때 this로 사용하는 값.

  • [예시]
const classmates=["jone","sally","jane"]
classmates.map(el => el+"입니다")
// 화살표함수이기 때문에 소괄호생략가능
// ['jone입니다', 'sally입니다', 'jane입니다']
const classmates = [
  {name:"jone"},
  {name:"sally"},
  {name:"jane"}
  ]
classmates.map(el => ({name:el.name + "입니다."}))
//[{name:"jone입니다"}, {name: 'sally입니다.'},{name: 'jane입니다.'}]

[화살표 함수형식]

const colors = ['red','yellow','blue']
const a = colors.map((color,index)=>({
    id:index,
    name:color
}));
a;
//result
[
  { id: 0, name: 'red' },
  { id: 1, name: 'yellow' },
  { id: 2, name: 'blue' }
]

배열 안의 객체 다루는 법!
중괄호와 리턴사이에 아무것도 없다면 소괄호로 바꿀 수 있으나
화살표함수의 시작중괄호가 되어버림
객체로 담아 감싸서 리턴해줘야 한다.

❗️ map과 filter의 공통점과 차이점

공통점은 기존배열은 건드리지 않으면서 요소들을 순회한 후 새로운 배열을 리턴한다는 것이고,
차이점은 map은 콜백함수가 적용된 새 요소, filter는 조건문을 만족한 요소들을 반환한다는 점이다.


💡.reduce()

✅ reduce

배열을 누적계산의 결과 값(단일값)으로 반환하는 함수로,
map과 filter와 같이 배열의 각 요소에 대해 콜백함수를 실행한다.

reduce는 리듀서 함수는 네 개의 인자를 가진다.
1. 누적기 (acc)
2. 현재 값 (cur)
3. 현재 인덱스 (idx)
4. 원본 배열 (src)

리듀서 함수의 반환 값은 누적기에 할당되고, 누적기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 된다.

  • [구문 형태]
arr.reduce(callback[, initialValue])

callback : 각 요소를 시험할 함수
element : 처리할 현재 요소
index(Optional) : 처리할 현재 요소의 인덱스.
array(Optional) : filter를 호출한 배열.
thisArg(Optional) : callback을 실행할 때 this로 사용하는 값.

  • [예시]
const pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];
const totalYears = pilots.reduce((acc,pilot)=>{
    return acc + pilot.years;
},0)
// 82

💡.every()

✅ every

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트하고 Boolean 값을 반환한다.

  • [예시]
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));

[출처 및 참조]

filter mdn
map mdn
https://medium.com/@jeff_long/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c
https://7942yongdae.tistory.com/49
https://bitcoins.tistory.com/23
https://velog.io/@tjdud0123/javascript-map-filter-%ED%95%A8%EC%88%98
https://velog.io/@decody/map-%EC%A0%95%EB%A6%AC
https://goddino.tistory.com/95
https://doqtqu.tistory.com/320

profile
JUST DO WHATEVER

0개의 댓글