将同一属性上的值分组-JavaScript
假设我们有一个像这样的数组-
const arr = [
{unit: 35, brand: 'CENTURY'},
{unit: 35, brand: 'BADGER'},
{unit: 25, brand: 'CENTURY'},
{unit: 15, brand: 'CENTURY'},
{unit: 25, brand: 'XEGAR'}
];我们需要编写一个函数,该函数对单位属性相同的对象的所有品牌属性进行分组。
像上面的数组一样,新数组应为-
const output = [
{unit: 35, brand: 'CENTURY, BADGER'},
{unit: 25, brand: 'CENTURY, XEGAR'},
{unit: 15, brand: 'CENTURY'}
];我们将遍历数组,使用辅助函数搜索具有单位值的对象。如果存在,则将品牌值连接起来,否则将创建一个新对象。
示例
以下是代码-
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' }
]