对相同属性的值进行分组 - JavaScript


假设我们有一个这样的数组 −

const arr = [
   {unit: 35, brand: 'CENTURY'},
   {unit: 35, brand: 'BADGER'},
   {unit: 25, brand: 'CENTURY'},
   {unit: 15, brand: 'CENTURY'},
   {unit: 25, brand: 'XEGAR'}
];

我们需要编写一个函数,该函数将 unit 属性相同的对象的所有 brand 属性进行分组。

对于上面这个数组,新数组应该是 −

const output = [
   {unit: 35, brand: 'CENTURY, BADGER'},
   {unit: 25, brand: 'CENTURY, XEGAR'},
   {unit: 15, brand: 'CENTURY'}
];

我们将循环遍历数组,使用一个辅助函数查找 unit 值的对象。如果它存在,我们就连接品牌值,否则创建一个新对象。

示例

以下是代码 −

const arr = [
   {unit: 35, brand: 'CENTURY'},
   {unit: 35, brand: 'BADGER'},
   {unit: 25, brand: 'CENTURY'},
   {unit: 15, brand: 'CENTURY'},
   {unit: 25, brand: 'XEGAR'}
];
const indexOf = function(unit){
   return this.findIndex(el => el.unit === unit)
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const ind = res.indexOf(arr[i].unit);
      if(ind !== -1){
         res[ind].brand += `, ${arr[i].brand}`;
      }else{
         res.push(arr[i]);
      }
   };
   return res;
};
console.log(groupArray(arr));

输出

这将在控制台中生成如下输出 −

[
   { unit: 35, brand: 'CENTURY, BADGER' },
   { unit: 25, brand: 'CENTURY, XEGAR' },
   { unit: 15, brand: 'CENTURY' }
]

更新于: 18-9月-2020

266 浏览次数

助力您的 事业

通过完成课程取得认证

开始学习
广告
© . All rights reserved.