假设我们有一个对象数组,其中包含有关某些水果和蔬菜的数据,例如:
const arr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
];我们需要编写一个包含一个这样的数组的JavaScript函数。
然后,我们的函数应根据对象的“类型”属性对数组对象进行分组。
这意味着将所有“水果”类型的对象分组在一起,而将“蔬菜”类型的对象分别分组在一起。
为此的代码将是-
const arr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
];
const transformArray = (arr = []) => {
const res = [];
const map = {};
let i, j, curr;
for (i = 0, j = arr.length; i < j; i++) {
curr = arr[i];
if (!(curr.type in map)) {
map[curr.type] = {type: curr.type, foods: []};
res.push(map[curr.type]);
};
map[curr.type].foods.push(curr.food);
};
return res;
};
console.log(transformArray(arr));输出结果
控制台中的输出将是-
[
{ type: 'fruit', foods: [ 'apple', 'banana' ] },
{ type: 'vegetable', foods: [ 'potato' ] }
]