简体   繁体   中英

how to create dynamic multi-dimensional array of objects with in javascript

I have an array of objects that has information about cars. I want to grouping on categoryId

var car = [
  { category: 1, model: "bmw" },
  { category: 1, model: "benz" },
  { category: 1, model: 'ford' }
  { category: 2, model: "kia" },
  { category: 2, model: "fiat" },
  { category: 3, model: "mg" },
];

I want this result

[  
  [
    { category: 1, model: 'bmw' },
    { category: 1, model: 'benz' },
    { category: 1, model: 'ford' }
  ],
  [ 
    { category: 2, model: 'kia' },
    { category: 2, model: 'fiat' }
  ],
  [ 
    { category: 3, model: 'mg' }
  ]
]

this is my solution but I want a way for this result based on reduce or... I dont want to use if in forEach

let groupedCars = [];
cars.forEach((car) => {
  if (!groupedCars[car.category]) {
    groupedCars[car.category] = [];
  }
  groupedCars[car.category].push(car);
});

Solution using Array.prototype.reduce() method. Traverse the array and group it by category using reduce and at last, use Object.values() to get the result.

 const car = [ { category: 1, model: 'bmw' }, { category: 1, model: 'benz' }, { category: 1, model: 'ford' }, { category: 2, model: 'kia' }, { category: 2, model: 'fiat' }, { category: 3, model: 'mg' }, ]; const ret = Object.values( car.reduce((prev, c) => { const p = prev; const key = c.category; p[key] = p[key]?? []; p[key].push({...c }); return p; }, {}) ); console.log(ret);

Not clear what you mean by result based on ES6 . But, you could try using reduce method.

NOTE : Javascript arrays start with index 0 so, you might need to add some logic in your code to fix that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM