reduce

์–ด๋–ค ๊ธฐ์ค€์— ์˜ํ•œ ๋ฐ์ดํ„ฐ๋“ค์„ groupํ•ด์„œ ๋ฐฐ์—ด์— ๋‹ด๊ธฐ

 var people = [
  { _id: 1,  name: 'iroMan', actor: '๋กœ๋ฒ„ํŠธ ๋‹ค์šฐ๋‹ˆ ์ฃผ๋‹ˆ์–ด', alias: '์•„์ด์–ด๋งจ', age: 21 },
  { _id: 2, name: 'Jane', actor:'toto', alias: 'dddd', age: 40 },
  { _id: 3, name: 'captainAmerica', actor:'ํฌ๋ฆฌ์Šค ์—๋ฐ˜์Šค', alias: '์บกํ‹ด ์•„๋ฉ”๋ฆฌ์นด', age: 40 },
  { _id: 4, name: 'captainAmerica', actor:'ํฌ๋ฆฌ์Šค ์—๋ฐ˜์Šค', alias: '์บกํ‹ด ์•„๋ฉ”๋ฆฌ์นด', age: 40 }
];
const groupBy = (objectArray, property) => {
return objectArray.reduce((acc, cur, idx) => {
    var key = cur[property];
    if(!acc[key]){      // ๋ˆ„์ ๋˜๋Š” age๊ฐ€ ์—†์œผ๋ฉด 
        acc[key] = [];  // ๋ˆ„์ ๋˜๋Š” age๋ฅผ key๋ช…์œผ๋กœ ๋นˆ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.
    }
     acc[key].push(cur);
     return acc;
}, {}); // acc์˜ ์ดˆ๊ธฐ ๊ฐ’ ๋นˆ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค. 1)
};

var groupedId = groupBy(people, '_id');
console.log(groupedId)

var groupedAge = groupBy(people, 'age');
console.log(groupedAge)

๋ฐฐ์—ด์˜ ๊ฐ ์›์†Œ์— ์›ํ•˜๋Š” ํ‚ค๋ช…์„ ๋„ฃ๊ธฐ

//  โŒ Bad Code
const groupBy = (objectArray) => {
     return objectArray.reduce((acc, cur, idx) => { 
          acc['key_'+ (idx + 1)] = cur    // ๋ฐฐ์—ด์˜ ๊ฐ ์›์†Œ์— ์›ํ•˜๋Š” ํ‚ค๋ช…์„ ๋„ฃ์–ด์„œ, 
          return acc;                     // acc๋ˆ„์ ๋œ ๊ฐ’์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
     }, {}); // acc์˜ ์ดˆ๊ธฐ ๊ฐ’ ๋นˆ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค. 1)
};

var groupedAge = groupBy(people);
console.log(groupedAge);
//  โœ… Good Code
const result = people.reduce((acc, cur, idx) => {
    return ({...acc, ['key_'+(idx+1)] : cur})
},{});

console.log(result);

์ด๋ ‡๊ฒŒ Spread Syntax ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์€์ ์€ ๋งŒ์•ฝ acc ๊ฐ’์„ ๋ฎ์–ด์”Œ์šฐ๊ณ  ์‹ถ๋‹ค๋ฉด , ์ฝค๋งˆ ๋’ค์—๋‹ค๊ฐ€ ์›ํ•˜๋Š” ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ๋ฅผ ํ• ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ฒฐ๊ณผ) ๐Ÿ‘‡๐Ÿ‘‡

Last updated