对同一属性上的值进行分组 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 23:08:17
假设我们有一个像这样的数组 −
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' }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

