forEach(), map(), filter(), some(), every(), find(), findIndex(), reduce() 배열 메소드와 병합필요

김종현·2023년 3월 19일
0

Js

목록 보기
3/16

https://developer-talk.tistory.com/261 배열을 비교하는 방법
https://arikong.tistory.com/19 every vs some

forEach

-callback 함수를 받아 배열을 순회하며, callback 함수를 배열의 각 요소에 대해 오름차순으로 한 번씩 실행.

arr.forEach(callback(currentvalue [, index[, array]])[, thisArg])

-map(), reduce()와 달리 undefined를 반환하므로 메서드 체인의 중간에 쓸 수 없음.

  • 변수로 결과를 받을 필요가 없다는 이야기.

-forEach 호출을 시작한 뒤 배열에 추가한 요소엔 callback이 방문x, 기존 요소값이 바뀐 경우 callback에 전달하는 값은 forEach가 요소를 방문한 시점의 값을 사용, 방문하기 전에 삭제한 요소는 방문하지 않음.

-예외를 심어두지 않는 이상 중간에 멈추지 않으므로 every(), some(), find(), findIndex() 등의 배열 메소드로 배열 요소를 판별 함수에 전달하여 참/거짓에 따라 조기 반복 종료 가능.

callback 함수의 파라미터

-forEach는 배열을 변형하지 않으나 callback이 변형할 수도 있음.

  • CurrentValue : 처리할 현재 요소
  • Index (선택적 매개변수) : 처리할 현재 요소의 인덱스
  • Array (선택적 매개변수) : forEach를 호출한 배열
  • thisArg : callback을 실행할 때 전달해 this로 사용할 값. 전달하지 않으면 undefined를 사용.

반환 값

-undefined. 없음. return 쓸 필요 없음.

기존 forconst numbers = [1, 2, 3, 4, 5];
for (i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

forEach문
numbers.forEach(function(el) {
console.log(el);
});
  
numbers.forEach(el => console.log(number));
function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// 인덱스 2는 배열의 그 위치에 항목이 없기에
// 건너뜀을 주의하세요.
[2, 5, , 9].forEach(logArrayElements);
// 기록:
// a[0] = 2
// a[1] = 5
// a[3] = 9

-삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않음

const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach(function(element){
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// 3과 7 사이에 없는 value는 callback이 계산하지 않음.

map

-배열의 각 요소에 대하여 주어진 함수를 수행한 결과를 모아 새로운 배열을 반환
-예) 단위변환(섭씨→화씨), 숫자→문자 등
-요소들에게 일괄적으로 함수를 적용하고 싶을 때 사용하기 적합

-map이 처리할 요소의 범위는 첫 callback을 호출하기 전에 정해집니다. map이 시작한 이후 배열에 추가되는 요소들은 callback을 호출하지 않습니다. 배열에 존재하는 요소들의 값이 바뀐 경우 map이 방문하는 시점의 값이 callback에 전달됩니다. map이 시작되고, 방문하기 전에 삭제된 요소들은 방문하지 않습니다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])

callback 함수의 파라미터

  • CurrentValue : 처리할 현재 요소
  • Index (선택적 매개변수) : 처리할 현재 요소의 인덱스
  • Array (선택적 매개변수) : map을 호출한 배열
  • thisArg (선택적 매개변수) : callback을 실행할 때 this로 사용되는 값.

thisArg 매개변수가 map에 전달된 경우 callback 함수의 this값으로 사용됩니다. 그 외의 경우 undefined값이 this 값으로 사용됩니다. callback 함수에서 최종적으로 볼 수 있는 this 값은 함수 내 this를 정하는 일반적인 규칙에 따라 결정됩니다.

callback 함수는 (undefined도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출. 즉, 값이 삭제되거나 아직 값이 할당/정의되지 않은 인덱스에 대해서는 호출되지 않음.

반환 값

-return을 써줘야 함.
-배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열.

const arr = [5, 1, 3, 2, 6];

function double(x) {
	return x * 2;
}
const output = arr.map(double);
// [10, 2, 6, 4, 12]

function triple(x) {
	return x * 3;
}
const output2 = arr.map(triple);
// [15, 3, 9, 6, 18]
function binary(x) {
	return x.toString("2");
}
const output3 = arr.map(binary);
// ["101, "1", "11", "10", "110"]
//배열 내 숫자들의 제곱근을 구하여 새로운 배열 출력
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots는 [1, 2, 3]
// numbers는 그대로 [1, 4, 9]

filter

-배열의 각 요소에 대하여 주어진 함수의 결괏값이 true인 요소를 모아 새로운 배열을 반환하는 메서드
-filter함수는 React 코드에서 DB의 자료를 가지고 왔을 때 특정 조건에 해당되는 것만 추려낼 때 쓰는 아주 유용한 함수

arr.filter(callback(element[, index[, array]])[, thisArg])
// arr에서 홀수만 뽑아내기
const arr = [5, 1, 3, 2, 6];
const output = arr.filter((x) => x % 2);

// arr에서 짝수만 뽑아내기
const arr = [5, 1, 3, 2, 6];
const output = arr.filter((x) => x % 2 === 0);

//부서가 it인 사람만 뽑아내기
let employees = [
{ id: 20, name: "Kim", salary: 30000, dept: "it" },
{ id: 24, name: "Park", salary: 35000, dept: "hr" },
{ id: 56, name: "Son", salary: 32000, dept: "it" },
{ id: 88, name: "Lee", salary: 38000, dept: "hr" },
];
let departmentList = employees.filter(function (record) {
return record.dept == "it";
});
console.log(departmentList);
[{
  dept: "it",
  id: 20,
  name: "Kim",
  salary: 30000
}, {
  dept: "it",
  id: 56,
  name: "Son",
  salary: 32000
}]

let nameList = employees.filter( (item) =>{
  return item.name.startsWith('K')}
);
console.log(nameList);
[{
  dept: "it",
  id: 20,
  name: "Kim",
  salary: 30000
}]

반환값

-조건에 true인 결과 값을 모두 배열로 반환

some()

-배열에서의 조건에 맞는 요소의 유무 판단에 씀.

let employees = [
{ id: 20, name: "Kim", salary: 30000, dept: "it" },
{ id: 24, name: "Park", salary: 35000, dept: "hr" },
{ id: 56, name: "Son", salary: 32000, dept: "it" },
{ id: 88, name: "Lee", salary: 38000, dept: "hr" },
];
let nameList = employees.some( (item) =>{
  return item.name.startsWith('K')}
);
console.log(nameList); // true

let nameList2 = employees.some( (item) =>{
  return item.name.startsWith('F')}
);
console.log(nameList2); // false

반환 값

-조건을 만족 한다면 true 반환.

every()

-배열의 모든 요소에 대한 조건 판단에 씀.

let employees = [
{ id: 20, name: "Kim", salary: 30000, dept: "it" },
{ id: 24, name: "Park", salary: 35000, dept: "hr" },
{ id: 56, name: "Son", salary: 32000, dept: "it" },
{ id: 88, name: "Lee", salary: 38000, dept: "hr" },
];
let nameList = employees.every( (item) =>{
  return item.name.startsWith('K')}
);
console.log(nameList); // false

let nameLength = employees.every( (item) =>{
  return item.name.length>0}
);
console.log(nameLength); // true

반환 값

-배열의 모든 요소가 조건을 만족하는지에 대해 boolean 반환.

find

let employees = [
{ id: 20, name: "Kim", salary: 30000, dept: "it" },
{ id: 24, name: "Park", salary: 35000, dept: "hr" },
{ id: 56, name: "Son", salary: 32000, dept: "it" },
{ id: 88, name: "Lee", salary: 38000, dept: "hr" },
];

let nameList = employees.find( (item) =>{
  return item.name.startsWith('K')}
);
console.log(nameList);

{
  dept: "it",
  id: 20,
  name: "Kim",
  salary: 30000
}

반환 값

-조건을 만족하는 item 하나만을 찾아서 반환.

findIndex

let employees = [
{ id: 20, name: "Kim", salary: 30000, dept: "it" },
{ id: 24, name: "Park", salary: 35000, dept: "hr" },
{ id: 56, name: "Son", salary: 32000, dept: "it" },
{ id: 88, name: "Lee", salary: 38000, dept: "hr" },
];

let nameList = employees.findIndex( (item) =>{
  return item.name.startsWith('K')}
);
console.log(nameList); // 0

반환 값

-조건에 부합하는 index의 번호

reduce

-배열 각 요소에 대하여 reducer 함수를 실행하고, 배열이 아닌 하나의 결괏값을 반환

arr.reduce(callback[, initialValue])

-빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 callback 함수를 한 번씩 실행

callback 함수의 파라미터

  • Accumulator : 콜백의 반환값을 누적. 첫 호출시 initialValue 값 가짐.

  • CurrentValue : 처리할 현재 요소

  • currentIndex (선택적 매개변수) : 처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작

  • Array (선택적 매개변수) : reduce를 호출한 배열

  • InitialValue (선택적 매개변수) : 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생

  • 배열이 비어있는데 initialValue도 제공하지 않으면 TypeError가 발생

  • 배열의 요소가 하나 뿐이면서 initialValue를 제공되지 않은 경우, 또는 initialValue는 주어졌으나 배열이 빈 경우엔 그 단독 값을 callback 호출 없이 반환

initialValue를 제공한 경우,

  • accumulator = initialValue
  • currentValue = Index[0]
    initialValue를 제공하지 않았다면,
  • accumulator = Index[0]
  • currentValue = Index[1]

반환 값

-Accumulator의 누적 계산 결과 값

const arr = [5, 1, 3, 2, 6];

// 합산 값 찾기
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// sum is 6

var total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0
);


// 객체 내 값 인스턴스 개수 세기
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }


//속성으로 객체 분류
var people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }


//배열 중복 항목 제거
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((accumulator, current) => {
    const length = accumulator.length
    if (length === 0 || accumulator[length - 1] !== current) {
        accumulator.push(current);
    }
    return accumulator;
}, []);
console.log(result); //[1,2,3,4,5]
profile
나는 나의 섬이다.

0개의 댓글