본문 바로가기
JavaScript

TIL 0925~26 arr.reduce() filter() map() sort() some() find()

by 짱닭 2020. 9. 25.
반응형

초기값을 줬을 때

arr.reduce( func( acc, val ) { ... } , initialValue );

acc에 initialValue가 들어가고
val엔 arr의 첫번째 요소가 들어간다.
이후론 val에 arr의 다음요소가 순서대로 들어가며 콜백함수를 반복.

초기값을 주지 않았을 때

arr.reduce( func( acc, val ) { ... });

acc에 arr의 첫번째 요소가 들어가고
val엔 arr의 두번째 요소가 들어간다.
이후론 val에 arr의 세번째 요소부터 순서대로 들어가며 콜백함수를 반복.

arr.reduce()예제

객체의 각 값도 접근해서 더할 수 있다.
reduce와 concat을 함께 사용한 예

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 }

위 예제처럼 allNames라는 새로운 객체에 값을 누적시키고 리턴하는 방법도 가능하다!

reduce()로 평균을 구하는 방법 5가지 + reduce()를 사용하지 않는 방법

function average(nums) {
    return nums.reduce((a, b) => (a + b)) / nums.length;
}
function isFound(item) {
    return item.found;
};

function getPopularity(item) {
    return item.popularity;
}

function addScores(runningTotal, popularity) {
    return runningTotal + popularity;
}

// Calculations
// ----------------------------------------------------------------------------

// Filter out terms that weren't found in books.
const foundSlangTerms = victorianSlang.filter(isFound);

// Extract the popularity scores so we just have an array of numbers.
const popularityScores = foundSlangTerms.map(getPopularity);

// Add up all the scores total. Note that the second parameter tells reduce
// to start the total at zero.
const scoresTotal = popularityScores.reduce(addScores, 0);

// Calculate the average and display.
const averagePopularity = scoresTotal / popularityScores.length;
console.log("Average popularity:", averagePopularity);
function isFound(item) {
    return item.found;
};

function getPopularity(item) {
    return item.popularity;
}

// We use an object to keep track of multiple values in a single return value.
function addScores({totalPopularity, itemCount}, popularity) {
    return {
        totalPopularity: totalPopularity + popularity,
        itemCount:       itemCount + 1,
    };
}

// Calculations
// ---------------------------------------------------------------------------------

const initialInfo    = {totalPopularity: 0, itemCount: 0};
const popularityInfo = victorianSlang.filter(isFound)
    .map(getPopularity)
    .reduce(addScores, initialInfo);

// Calculate the average and display.
const {totalPopularity, itemCount} = popularityInfo;
const averagePopularity = totalPopularity / itemCount;
console.log("Average popularity:", averagePopularity);
const filter  = p => a => a.filter(p);
const map     = f => a => a.map(f);
const prop    = k => x => x[k];
const reduce  = r => i => a => a.reduce(r, i);
const compose = (...fns) => (arg) => fns.reduceRight((arg, fn) => fn(arg), arg);

// Lift for functions.
// See: https://jrsinclair.com/articles/2019/compose-js-functions-multiple-parameters/
const lift = f => g => h => x => f(g(x))(h(x));

// Calculations
// ----------------------------------------------------------------------------

// We'll create a sum function that adds all the items of an array together.
const sum = reduce((a, i) => a + i)(0);

// A function to get the length of an array.
const length = a => a.length;

// A function to divide one number by another.
const div = a => b => a / b;

// We use compose() to piece our function together using the small helpers.
// With compose() you read from the bottom up.
const calcPopularity = compose(
    lift(div)(sum)(length),
    map(prop('popularity')),
    filter(prop('found')),
);

const averagePopularity = calcPopularity(victorianSlang);
console.log("Average popularity:", averagePopularity);
function averageScores({avg, n}, slangTermInfo) {
    if (!slangTermInfo.found) {
        return {avg, n};
    }
    return {
        avg: (slangTermInfo.popularity + n * avg) / (n + 1),
        n:   n + 1,
    };
}

// Calculations
// ----------------------------------------------------------------------------

// Calculate the average and display.
const initialVals       = {avg: 0, n: 0};
const averagePopularity = victorianSlang.reduce(averageScores, initialVals).avg;
console.log("Average popularity:", averagePopularity);

출처 : jrsinclair.com/articles/2019/five-ways-to-average-with-js-reduce/

.filter() 문법 3가지

// 1.
let newarr = arr.filter(function(요소){ 
  return 요소와 비교할조건식;
});

// 2.
function functionName(){
return 조건식;
}
let newarr = arr.filter(functionName);

// 3.
let newarr = arr.filter(요소 => 요소와 비교할 조건식);

arr.filter()는 arr(원본)의 값을 바꾸지 않고 인자로 전달된 조건에 맞는 배열의 요소만 새로운 배열에 리턴한다.

.map()

원본배열의 요소를 편집(수정)한 새로운 배열을 리턴

  let newArr = arr.map(function(ele){
    ele = ele + 3;
  });

원소 하나하나 순환하며 공통된 작업을 수행해야 할 때 사용한다.
리턴문을 사용하지 않고 원본의 특정 값만 수정할 수 있다.

.concat()

아래 예를 응용해서 2차원 배열을 1차원으로 이어붙이는 것도 가능하다.

.sort()

.some()

.find()

반응형

댓글