"자바스크립트 groupBy()"의 두 판 사이의 차이

16번째 줄: 16번째 줄:


==직접 구현==
==직접 구현==
<syntaxhighlight lang='console'>
<syntaxhighlight lang='javascript' run>
function groupBy(array, key) {
function groupBy(array, key) {
   return array.reduce((result, currentValue) => {
   return array.reduce((result, currentValue) => {

2024년 2월 12일 (월) 18:14 판

1 개요

자바스크립트 groupBy()

2 Object.groupBy()

const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];
const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result);

3 직접 구현

function groupBy(array, key) {
  return array.reduce((result, currentValue) => {
    const groupKey = currentValue[key];
   if (!result[groupKey]) {
      result[groupKey] = [];
    }
    result[groupKey].push(currentValue);
    return result;
  }, {});
}

const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];
const result = groupBy(inventory, 'type');
console.log(result);

4 같이 보기

5 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}