Case: JS uses the reduce method to classify array objects

Using the reduce method can quickly implement operations classified by attributes, which is more efficient than using loop iterations. Here is a simple sample code:

const arr = [
  {
    
     id: 1, name: 'A' },
  {
    
     id: 2, name: 'B' },
  {
    
     id: 3, name: 'A' },
  {
    
     id: 4, name: 'C' },
  {
    
     id: 5, name: 'B' },
];

const result = arr.reduce((acc, item) => {
    
    
  const key = item.name;
  if (!acc[key]) {
    
    
    acc[key] = [];
  }
  acc[key].push(item);
  return acc;
}, {
    
    });

console.log(result);
/* 
{
  A: [{ id: 1, name: 'A' }, { id: 3, name: 'A' }],
  B: [{ id: 2, name: 'B' }, { id: 5, name: 'B' }],
  C: [{ id: 4, name: 'C' }]
} 
*/
console.log(Object.entries(result));

In this example, use the reduce method to iterate over the array, use the name attribute of each element as the key, add the corresponding element to the array named by key, and finally return an object with the attribute value as the key.
Finally, the result is converted into a two-dimensional array through the Object.entries() method and output.

Guess you like

Origin blog.csdn.net/m0_37577465/article/details/130420592
Recommended