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

(새 문서: ==개요== ;자바스크립트 Object.groupBy() <syntaxhighlight lang='javascript' run> const inventory = [ { name: "asparagus", type: "vegetables", quantity: 5 }, { name: "banan...)
 
 
(같은 사용자의 중간 판 3개는 보이지 않습니다)
1번째 줄: 1번째 줄:
==개요==
==개요==
;자바스크립트 Object.groupBy()
;자바스크립트 groupBy()


==Object.groupBy()==
<syntaxhighlight lang='javascript'>
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);
</syntaxhighlight>
==직접 구현==
<syntaxhighlight lang='javascript' run>
<syntaxhighlight lang='javascript' run>
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 = [
const inventory = [
   { name: "asparagus", type: "vegetables", quantity: 5 },
   { name: "asparagus", type: "vegetables", quantity: 5 },
10번째 줄: 35번째 줄:
   { name: "fish", type: "meat", quantity: 22 },
   { name: "fish", type: "meat", quantity: 22 },
];
];
const result = Object.groupBy(inventory, ({ type }) => type);
const result = groupBy(inventory, 'type');
console.log(result);
console.log(result);
</syntaxhighlight>
</syntaxhighlight>

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 }}