对相同属性的值进行分组 - 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' }
]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP