有人知道一种方法(lodash如果可能的话)通过对象键分组对象数组,然后根据分组创建一个新的对象数组吗?例如,我有一个汽车对象数组:

const 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'
    },
];

我想创建一个新的汽车对象数组,由make分组:

const cars = {
    'audi': [
        {
            'model': 'r8',
            'year': '2012'
        }, {
            'model': 'rs5',
            'year': '2013'
        },
    ],

    'ford': [
        {
            'model': 'mustang',
            'year': '2012'
        }, {
            'model': 'fusion',
            'year': '2015'
        }
    ],

    'kia': [
        {
            'model': 'optima',
            'year': '2012'
        }
    ]
}

您正在寻找_.groupBy()。

如果需要,从对象中删除分组的属性应该很简单:

Const cars = [{ “做”:“奥迪”, “模型”:“r8”, “年”:“2012” },{ “做”:“奥迪”, “模型”:“生活费”, “年”:“2013” },{ “做”:“福特”, “模型”:“野马”, “年”:“2012” },{ “做”:“福特”, “模型”:“融合”, “年”:“2015” },{ “做”:“克钦独立军”, “模型”:“最佳状态”, “年”:“2012” }); Const分组= _。groupBy(cars, car => car.make); console.log(分组); < script src = " https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js " > < /脚本>


在简单的Javascript中,你可以使用array# reduce对象

Var cars = [{make: 'audi',型号:'r8',年份:'2012'},{make: 'audi',型号:'rs5',年份:'2013'},{make: 'ford',型号:'mustang',年份:'2012'},{make: 'ford',型号:'fusion',年份:'2015'},{make: 'kia',型号:'optima',年份:'2012'}], 结果=汽车。Reduce(函数(r, a) { r (a。Make] = r[a]。Make] || []; r (a.make) .push(一个); 返回r; }, Object.create (null)); console.log(结果); .as-console-wrapper {max-height: 100% !重要;上图:0;}


提莫的答案是我会怎么做。简单的_。groupBy,并允许在分组结构中的对象中有一些重复。

然而,OP还要求删除重复的make键。如果你想从头到尾:

var grouped = _.mapValues(_.groupBy(cars, 'make'),
                          clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);

收益率:

{ audi:
   [ { model: 'r8', year: '2012' },
     { model: 'rs5', year: '2013' } ],
  ford:
   [ { model: 'mustang', year: '2012' },
     { model: 'fusion', year: '2015' } ],
  kia: 
   [ { model: 'optima', year: '2012' } ] 
}

如果你想使用Underscore.js来实现这个功能,请注意它的_. js版本。mapValues被称为_.mapObject。


您可以尝试在调用per iteration的函数中修改对象_。groupBy func。 注意,源数组改变了它的元素!

var res = _.groupBy(cars,(car)=>{
    const makeValue=car.make;
    delete car.make;
    return makeValue;
})
console.log(res);
console.log(cars);

完全没有理由下载第三方库来解决这个简单的问题,就像上面的解决方案所建议的那样。

在es6中按特定键对对象列表进行分组的单行版本:

const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})

较长的版本过滤掉没有键的对象:

function groupByKey(array, key) { return array .reduce((hash, obj) => { if(obj[key] === undefined) return hash; return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}) }, {}) } 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'}]; console.log(groupByKey(cars, 'make'))

注意:原来的问题似乎是问如何按制造商对汽车进行分组,但省略了每组中的制造商。因此,如果没有第三方库,简单的回答是这样的:

const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {}) 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'}]; console.log(groupByKey(cars, 'make', {omitKey:true}))


下面是您自己的groupBy函数,它是来自https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore的代码的泛化

函数groupBy(xs, f) { 返回x。减少((r, v, i, a、k = f (v)) = > ((r [k] | | (r [k] = [])) .push (v), r), {}); } Const cars = [{make: 'audi',型号:'r8',年份:'2012'},{make: 'audi',型号:'rs5',年份:'2013'},{make: 'ford',型号:'mustang',年份:'2012'},{make: 'ford',型号:'fusion',年份:'2015'},{make: 'kia',型号:'optima',年份:'2012'}]; const result = groupBy(cars, (c) => c.make); console.log(结果);


你也可以像这样使用数组#forEach()方法:

const 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' }]; let newcars = {} cars.forEach(car => { newcars[car.make] ? // check if that array exists or not in newcars object newcars[car.make].push({model: car.model, year: car.year}) // just push : (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push }) console.log(newcars);


简单的for循环也可以实现:

 const result = {};

 for(const {make, model, year} of cars) {
   if(!result[make]) result[make] = [];
   result[make].push({ model, year });
 }

我用REAL GROUP BY作为JS数组的例子和这个任务完全一样

const inputArray = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ]; var outObject = inputArray.reduce(function(a, e) { // GROUP BY estimated key (estKey), well, may be a just plain key // a -- Accumulator result object // e -- sequentally checked Element, the Element that is tested just at this itaration // new grouping name may be calculated, but must be based on real value of real field let estKey = (e['Phase']); (a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e); return a; }, {}); console.log(outObject);


创建一个可以重用的方法

Array.prototype.groupBy = function(prop) {
      return this.reduce(function(groups, item) {
        const val = item[prop]
        groups[val] = groups[val] || []
        groups[val].push(item)
        return groups
      }, {})
    };

下面你可以根据任何标准进行分组

const groupByMake = cars.groupBy('make');
        console.log(groupByMake);

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' }, ]; //re-usable method Array.prototype.groupBy = function(prop) { return this.reduce(function(groups, item) { const val = item[prop] groups[val] = groups[val] || [] groups[val].push(item) return groups }, {}) }; // initiate your groupBy. Notice the recordset Cars and the field Make.... const groupByMake = cars.groupBy('make'); console.log(groupByMake); //At this point we have objects. You can use Object.keys to return an array


function groupBy(data, property) {
  return data.reduce((acc, obj) => {
    const key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
groupBy(people, 'age');

我喜欢@metakunfu的答案,但它并没有提供预期的输出。 下面是在最终的JSON有效负载中去除“make”的更新。

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'
    },
];

result = cars.reduce((h, car) => Object.assign(h, { [car.make]:( h[car.make] || [] ).concat({model: car.model, year: car.year}) }), {})

console.log(JSON.stringify(result));

输出:

{  
   "audi":[  
      {  
         "model":"r8",
         "year":"2012"
      },
      {  
         "model":"rs5",
         "year":"2013"
      }
   ],
   "ford":[  
      {  
         "model":"mustang",
         "year":"2012"
      },
      {  
         "model":"fusion",
         "year":"2015"
      }
   ],
   "kia":[  
      {  
         "model":"optima",
         "year":"2012"
      }
   ]
}

试试这个吧,我觉得挺好用的。

让分组= _。groupBy(汽车,“使”);

注意:使用lodash lib,所以包括它。


Var汽车= [{ :“奥迪”, 模型:“r8”, :“2012” },{ :“奥迪”, 模型:“生活费”, :“2013” },{ :“福特”, 模型:“野马”, :“2012” },{ :“福特”, 模型:“融合”, :“2015” },{ :“克钦独立军”, 模型:“最佳状态”, :“2012” })。Reduce ((r, car) => { const { 模型中, 一年, 使 } =汽车; R [make] =[…]R [make] || [], { 模型中, 一年 }); 返回r; }, {}); console.log(汽车);


对于key可以为null的情况,我们希望将它们分组为其他

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'},
            {'make':'kia','model':'optima','year':'2033'},
            {'make':null,'model':'zen','year':'2012'},
            {'make':null,'model':'blue','year':'2017'},

           ];


 result = cars.reduce(function (r, a) {
        key = a.make || 'others';
        r[key] = r[key] || [];
        r[key].push(a);
        return r;
    }, Object.create(null));

使用lodash/fp,你可以使用_.flow()创建一个函数,它首先按键分组,然后映射每个组,并从每个项中省略一个键:

const { flow, groupBy, mapValues, map, omit } = _; const groupAndOmitBy = key => flow( groupBy(key), mapValues(map(omit(key))) ); const 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' }]; const groupAndOmitMake = groupAndOmitBy('make'); const result = groupAndOmitMake(cars); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>


根据@Jonas_Wilms的回答,如果你不想输入所有的字段:

    var result = {};

    for ( let { first_field, ...fields } of your_data ) 
    { 
       result[first_field] = result[first_field] || [];
       result[first_field].push({ ...fields }); 
    }

我没有做任何基准测试,但我相信使用for循环会比这个答案中建议的任何方法都更有效。


const reGroup = (list, key) => {
    const newGroup = {};
    list.forEach(item => {
        const newItem = Object.assign({}, item);
        delete newItem[key];
        newGroup[item[key]] = newGroup[item[key]] || [];
        newGroup[item[key]].push(newItem);
    });
    return newGroup;
};
const animals = [
  {
    type: 'dog',
    breed: 'puddle'
  },
  {
    type: 'dog',
    breed: 'labradoodle'
  },
  {
    type: 'cat',
    breed: 'siamese'
  },
  {
    type: 'dog',
    breed: 'french bulldog'
  },
  {
    type: 'cat',
    breed: 'mud'
  }
];
console.log(reGroup(animals, 'type'));
const 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'
  },
];

console.log(reGroup(cars, 'make'));

Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

Array.prototype.groupBy = function(k) {
  return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};

const projs = [
  {
    project: "A",
    timeTake: 2,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 4,
    desc: "this is a description"
  },
  {
    project: "A",
    timeTake: 12,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 45,
    desc: "this is a description"
  }
];

console.log(projs.groupBy("project"));

这是另一个解决方案。按照要求。

我想创建一个新的汽车对象数组,由make分组:

function groupBy() {
  const key = 'make';
  return cars.reduce((acc, x) => ({
    ...acc,
    [x[key]]: (!acc[x[key]]) ? [{
      model: x.model,
      year: x.year
    }] : [...acc[x[key]], {
      model: x.model,
      year: x.year
    }]
  }), {})
}

输出:

console.log('Grouped by make key:',groupBy())

下面是一个受到Java中的collections . groupingby()启发的解决方案:

function groupingBy(list, keyMapper) { 返回列表。reduce((accummalatorMap, currentValue) => { const key = keyMapper(currentValue); 如果(! accummalatorMap.has(键)){ accummalatorMap。集(关键,[currentValue]); }其他{ accummalatorMap。集(键,accummalatorMap.get(关键).push (currentValue)); } 返回accummalatorMap; }, new Map()); }

这将给出一个Map对象。

/ /使用 const cars = groupingBy(cars, car => car.make);


对象的分组数组在typescript中:

groupBy (list: any[], key: string): Map<string, Array<any>> {
    let map = new Map();
    list.map(val=> {
        if(!map.has(val[key])){
            map.set(val[key],list.filter(data => data[key] == val[key]));
        }
    });
    return map;
});

我喜欢写它没有依赖/复杂性,只是纯粹的简单js。

const mp = {} const cars = [ { model: 'Imaginary space craft SpaceX model', year: '2025' }, { 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' } ] cars.forEach(c => { if (!c.make) return // exit (maybe add them to a "no_make" category) if (!mp[c.make]) mp[c.make] = [{ model: c.model, year: c.year }] else mp[c.make].push({ model: c.model, year: c.year }) }) console.log(mp)


我制定了一个基准测试不使用外部库的每个解决方案的性能。

JSBen.ch

由@Nina Scholz发布的reduce()选项似乎是最佳选项。


同意除非经常使用这些库,否则不需要外部库。虽然有类似的解决方案,但我发现其中一些很难遵循。如果您试图理解正在发生的事情,这里有一个带有注释的解决方案的要点。

const 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' }, ]; /** * Groups an array of objects by a key an returns an object or array grouped by provided key. * @param array - array to group objects by key. * @param key - key to group array objects by. * @param removeKey - remove the key and it's value from the resulting object. * @param outputType - type of structure the output should be contained in. */ const groupBy = ( inputArray, key, removeKey = false, outputType = {}, ) => { return inputArray.reduce( (previous, current) => { // Get the current value that matches the input key and remove the key value for it. const { [key]: keyValue } = current; // remove the key if option is set removeKey && keyValue && delete current[key]; // If there is already an array for the user provided key use it else default to an empty array. const { [keyValue]: reducedValue = [] } = previous; // Create a new object and return that merges the previous with the current object return Object.assign(previous, { [keyValue]: reducedValue.concat(current) }); }, // Replace the object here to an array to change output object to an array outputType, ); }; console.log(groupBy(cars, 'make', true))


只需简单的forEach循环就可以在这里工作,不需要任何库

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' }, ]; let ObjMap ={}; cars.forEach(element => { var makeKey = element.make; if(!ObjMap[makeKey]) { ObjMap[makeKey] = []; } ObjMap[makeKey].push({ model: element.model, year: element.year }); }); console.log(ObjMap);


另一个解决方案:

Var汽车= [ {“使”:“奥迪”,“模型”:“r8”,“年”:“2012”},{“使”:“奥迪”,“模型”:“生活费”,“年”:“2013”}, {“使”:“福特”,“模型”:“野马”,“年”:“2012”},{“使”:“福特”,“模型”:“融合”,“年”:“2015”}, {'make': 'kia','model': 'optima','year': '2012'}, ]; const reducedCars =汽车。Reduce ((acc, {make, model, year}) => ( { acc, [make]: acc[make] ?[…Acc [make], {model, year}]: [{model, year}], } ), {}); console.log (reducedCars);


添加Array.prototype.group和Array.prototype.groupToMap的提案现在处于阶段3!

当它达到阶段4并在大多数主流浏览器上实现时,你将能够这样做:

const 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' }
];

const grouped = cars.group(item => item.make);
console.log(grouped);

这将输出:

{
  audi: [
    { make: 'audi', model: 'r8', year: '2012' },
    { make: 'audi', model: 'rs5', year: '2013' }
  ],
  ford: [
    { make: 'ford', model: 'mustang', year: '2012' },
    { make: 'ford', model: 'fusion', year: '2015' }
  ],
  kia: [
    { make: 'kia', model: 'optima', year: '2012' }
  ]
}

在那之前,你可以使用这个core-js polyfill:

const 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' } ]; const grouped = cars.group(item => item.make); //console.log(grouped); // Optional: remove the "make" property from resulting object const entriesUpdated = Object .entries(grouped) .map(([key, value]) => [ key, value.map(({make, ...rest}) => rest) ]); const noMake = Object.fromEntries(entriesUpdated); console.log(noMake); <script src="https://unpkg.com/core-js-bundle@3.26.1/minified.js"></script>


@metakungfu answer略有不同,主要区别在于它从结果对象中省略了原始键,因为在某些情况下对象本身不再需要它,因为它现在在父对象中可用。

const groupBy = (_k, a) => a.reduce((r, {[_k]:k, ...p}) => ({
    ...r, ...{[k]: (
        r[k] ? [...r[k], {...p}] : [{...p}]
    )}
}), {});

考虑到您的原始输入对象:

console.log(groupBy('make', cars));

会导致:

{
  audi: [
    { model: 'r8', year: '2012' },
    { model: 'rs5', year: '2013' }
  ],
  ford: [
    { model: 'mustang', year: '2012' },
    { model: 'fusion', year: '2015' }
  ],
  kia: [
    { model: 'optima', year: '2012' }
  ]
}

const groupBy = (array, callback) => {
  const groups = {};
  
  array.forEach((element) => {
    const groupName = callback(element);
    if (groupName in groups) {
      groups[groupName].push(element);
    } else {
      groups[groupName] = [element];
    }
  });
  
  return groups;
};

或者花哨的裤子:

(() => {
  Array.prototype.groupBy = function (callback) {
    const groups = {};
    this.forEach((element, ...args) => {
      const groupName = callback(element, ...args);
      if (groupName in groups) {
        groups[groupName].push(element);
      } else {
        groups[groupName] = [element];
      }
    });

    return groups;
  };
})();

const res = [{ name: 1 }, { name: 1 }, { name: 0 }].groupBy(({ name }) => name);

// const res = {
//   0: [{name: 0}],
//   1: [{name: 1}, {name: 1}]
// }

这是一个MDN阵列的填充。groupBy函数。


letfinaldata=[]

let data =[{id:1,name:"meet"},{id:2,name:"raj"},{id:1,name:"hari"},{id:3,name:"hari"},{id:2,name:"ram"}]

data = data.map((item)=> 
{
    return {...item,
        name: [item.name]
    }
}) // Converting the name key from string to array


let temp = [];

for(let i =0 ;i<data.length;i++)
{
    const index = temp.indexOf(data[i].id) // Checking if the object id is already present
    if(index>=0)
    {
        letfinaldata[index].name = [...letfinaldata[index].name,...data[i].name] // If present then append the name to the name of that object
    }
    else{
        temp.push(data[i].id); // Push the checked object id
        letfinaldata.push({...data[i]}) // Push the object
    }
}

console.log(letfinaldata)

输出

[ { id: 1, name: [ 'meet', 'hari' ] },
  { id: 2, name: [ 'raj', 'ram' ] },
  { id: 3, name: [ 'hari' ] } ]

这是一个通用函数,将返回Array groupBy自己的键。

const getSectionListGroupedByKey = < T > ( property: keyof T, List: Array < T > ): Array < { title: T[keyof T];data: Array < T > } > => { const sectionList: Array < { title: T[keyof T];data: Array < T > } > = []; if (!property || !List ? .[0] ? .[property]) { return []; } const groupedTxnListMap: Map < T[keyof T], Array < T >> = List.reduce((acc, cv) => { const keyValue: T[keyof T] = cv[property]; if (acc.has(keyValue)) { acc.get(keyValue) ? .push(cv); } else { acc.set(keyValue, [cv]); } return acc; }, new Map < T[keyof T], Array < T >> ()); groupedTxnListMap.forEach((value, key) => { sectionList.push({ title: key, data: value }); }); return sectionList; }; // Example const 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' }, ]; const result = getSectionListGroupedByKey('make', cars); console.log('result: ', result)