Reducing/Grouping an array in Javascript

前端 未结 2 1724
误落风尘
误落风尘 2021-01-29 15:06

Based on this example, I want to group by object in a slightly other way. The outcome should be as follows:

[{
  key: \"audi\"
  items: [
    {
      \"make\": \         


        
2条回答
  •  遇见更好的自我
    2021-01-29 15:58

    You could use a hash table for grouping by make and an array for the wanted result.

    For every group in hash, a new object, like

    {
        key: a.make,
        items: []
    }
    

    is created and pushed to the result set.

    The hash table is initialized with a really empty object. There are no prototypes, to prevent collision.

    var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],
        hash = Object.create(null),
        result = [];
    
    cars.forEach(function (a) {
        if (!hash[a.make]) {
            hash[a.make] = { key: a.make, items: [] };
            result.push(hash[a.make]);
        }
        hash[a.make].items.push(a);
    });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题