按数组中的对象分组最有效的方法是什么?
例如,给定此对象数组:
[
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]
我正在表格中显示这些信息。我想通过不同的方法进行分组,但我想对值求和。
我将Undercore.js用于其groupby函数,这很有用,但并不能完成全部任务,因为我不希望它们“拆分”,而是“合并”,更像SQL groupby方法。
我要找的是能够合计特定值(如果需要)。
因此,如果我按阶段分组,我希望收到:
[
{ Phase: "Phase 1", Value: 50 },
{ Phase: "Phase 2", Value: 130 }
]
如果我组了阶段/步骤,我会收到:
[
{ Phase: "Phase 1", Step: "Step 1", Value: 15 },
{ Phase: "Phase 1", Step: "Step 2", Value: 35 },
{ Phase: "Phase 2", Step: "Step 1", Value: 55 },
{ Phase: "Phase 2", Step: "Step 2", Value: 75 }
]
是否有一个有用的脚本,或者我应该坚持使用Undercore.js,然后遍历生成的对象,自己计算总数?
发帖是因为即使这个问题已经7年了,我仍然没有看到一个符合原始标准的答案:
我不希望它们“拆分”,而是“合并”,更像SQL组方法
我最初发表这篇文章是因为我想找到一种方法来减少对象数组(例如,当您从csv中读取时创建的数据结构),并通过给定索引聚合以生成相同的数据结构。我正在寻找的返回值是另一个对象数组,而不是我在这里看到的嵌套对象或映射。
下面的函数获取一个数据集(对象数组)、一个索引列表(数组)和一个reducer函数,并将reducer功能应用于索引的结果作为一个对象数组返回。
function agg(data, indices, reducer) {
// helper to create unique index as an array
function getUniqueIndexHash(row, indices) {
return indices.reduce((acc, curr) => acc + row[curr], "");
}
// reduce data to single object, whose values will be each of the new rows
// structure is an object whose values are arrays
// [{}] -> {{}}
// no operation performed, simply grouping
let groupedObj = data.reduce((acc, curr) => {
let currIndex = getUniqueIndexHash(curr, indices);
// if key does not exist, create array with current row
if (!Object.keys(acc).includes(currIndex)) {
acc = {...acc, [currIndex]: [curr]}
// otherwise, extend the array at currIndex
} else {
acc = {...acc, [currIndex]: acc[currIndex].concat(curr)};
}
return acc;
}, {})
// reduce the array into a single object by applying the reducer
let reduced = Object.values(groupedObj).map(arr => {
// for each sub-array, reduce into single object using the reducer function
let reduceValues = arr.reduce(reducer, {});
// reducer returns simply the aggregates - add in the indices here
// each of the objects in "arr" has the same indices, so we take the first
let indexObj = indices.reduce((acc, curr) => {
acc = {...acc, [curr]: arr[0][curr]};
return acc;
}, {});
reduceValues = {...indexObj, ...reduceValues};
return reduceValues;
});
return reduced;
}
我将创建一个返回count(*)和sum(Value)的reducer:
reducer = (acc, curr) => {
acc.count = 1 + (acc.count || 0);
acc.value = +curr.Value + (acc.value|| 0);
return acc;
}
最后,使用我们的reducer将agg函数应用于原始数据集会生成一个应用了适当聚合的对象数组:
agg(tasks, ["Phase"], reducer);
// yields:
Array(2) [
0: Object {Phase: "Phase 1", count: 4, value: 50}
1: Object {Phase: "Phase 2", count: 4, value: 130}
]
agg(tasks, ["Phase", "Step"], reducer);
// yields:
Array(4) [
0: Object {Phase: "Phase 1", Step: "Step 1", count: 2, value: 15}
1: Object {Phase: "Phase 1", Step: "Step 2", count: 2, value: 35}
2: Object {Phase: "Phase 2", Step: "Step 1", count: 2, value: 55}
3: Object {Phase: "Phase 2", Step: "Step 2", count: 2, value: 75}
]
如果您需要通过以下方式进行多组:
const populate = (entireObj, keys, item) => {
let keysClone = [...keys],
currentKey = keysClone.shift();
if (keysClone.length > 0) {
entireObj[item[currentKey]] = entireObj[item[currentKey]] || {}
populate(entireObj[item[currentKey]], keysClone, item);
} else {
(entireObj[item[currentKey]] = entireObj[item[currentKey]] || []).push(item);
}
}
export const groupBy = (list, key) => {
return list.reduce(function (rv, x) {
if (typeof key === 'string') (rv[x[key]] = rv[x[key]] || []).push(x);
if (typeof key === 'object' && key.length) populate(rv, key, x);
return rv;
}, {});
}
const myPets = [
{name: 'yaya', type: 'cat', color: 'gray'},
{name: 'bingbang', type: 'cat', color: 'sliver'},
{name: 'junior-bingbang', type: 'cat', color: 'sliver'},
{name: 'jindou', type: 'cat', color: 'golden'},
{name: 'dahuzi', type: 'dog', color: 'brown'},
];
// run
groupBy(myPets, ['type', 'color']));
// you will get object like:
const afterGroupBy = {
"cat": {
"gray": [
{
"name": "yaya",
"type": "cat",
"color": "gray"
}
],
"sliver": [
{
"name": "bingbang",
"type": "cat",
"color": "sliver"
},
{
"name": "junior-bingbang",
"type": "cat",
"color": "sliver"
}
],
"golden": [
{
"name": "jindou",
"type": "cat",
"color": "golden"
}
]
},
"dog": {
"brown": [
{
"name": "dahuzi",
"type": "dog",
"color": "brown"
}
]
}
};
使用ES6的简单解决方案:
该方法有一个返回模型,可以比较n个财产。
const compareKey = (item, key, compareItem) => {
return item[key] === compareItem[key]
}
const handleCountingRelatedItems = (listItems, modelCallback, compareKeyCallback) => {
return listItems.reduce((previousValue, currentValue) => {
if (Array.isArray(previousValue)) {
const foundIndex = previousValue.findIndex(item => compareKeyCallback(item, currentValue))
if (foundIndex > -1) {
const count = previousValue[foundIndex].count + 1
previousValue[foundIndex] = modelCallback(currentValue, count)
return previousValue
}
return [...previousValue, modelCallback(currentValue, 1)]
}
if (compareKeyCallback(previousValue, currentValue)) {
return [modelCallback(currentValue, 2)]
}
return [modelCallback(previousValue, 1), modelCallback(currentValue, 1)]
})
}
const itemList = [
{ type: 'production', human_readable: 'Production' },
{ type: 'test', human_readable: 'Testing' },
{ type: 'production', human_readable: 'Production' }
]
const model = (currentParam, count) => ({
label: currentParam.human_readable,
type: currentParam.type,
count
})
const compareParameter = (item, compareValue) => {
const isTypeEqual = compareKey(item, 'type', compareValue)
return isTypeEqual
}
const result = handleCountingRelatedItems(itemList, model, compareParameter)
console.log('Result: \n', result)
/** Result:
[
{ label: 'Production', type: 'production', count: 2 },
{ label: 'Testing', type: 'testing', count: 1 }
]
*/
您可以从array.reduce()构建ES6映射。
const groupedMap = initialArray.reduce(
(entryMap, e) => entryMap.set(e.id, [...entryMap.get(e.id)||[], e]),
new Map()
);
这与其他解决方案相比有一些优势:
它不需要任何库(与例如_.groupBy()不同)您得到的是JavaScript Map而不是对象(例如,由_.groupBy()返回)。这有很多好处,包括:它会记住第一次添加项目的顺序,键可以是任何类型,而不仅仅是字符串。Map是比数组数组更有用的结果。但是,如果确实需要数组数组,则可以调用array.from(groupedMap.entries())(对于[key,group array]对的数组)或array.from(groupedMap.values()),(对于简单的数组数组)。它非常灵活;通常情况下,您计划使用此地图进行的任何操作都可以作为缩减的一部分直接完成。
作为最后一点的示例,假设我有一个对象数组,我想按id对其进行(浅)合并,如下所示:
const objsToMerge = [{id: 1, name: "Steve"}, {id: 2, name: "Alice"}, {id: 1, age: 20}];
// The following variable should be created automatically
const mergedArray = [{id: 1, name: "Steve", age: 20}, {id: 2, name: "Alice"}]
要做到这一点,我通常首先按id分组,然后合并每个结果数组。相反,您可以直接在reduce()中执行合并:
const mergedArray = Array.from(
objsToMerge.reduce(
(entryMap, e) => entryMap.set(e.id, {...entryMap.get(e.id)||{}, ...e}),
new Map()
).values()
);
稍后编辑:
对于大多数目的来说,上述方法可能足够有效。但最初的问题是“最有效”的,正如一些人所指出的,上述解决方案并非如此。问题主要是为每个条目实例化一个新数组。我本以为JS解释器会优化这一点,但似乎并非如此。
有人建议进行编辑来解决这个问题,但看起来确实更复杂。原始代码段已经有点提高了可读性。如果你真的想这样做,请使用for循环!这不是罪!它需要一到两行代码,但它比函数技术更简单,尽管它并不短:
groupedMap = new Map();
for (const e of initialArray) {
if (groupedMap.has(e.id)) {
groupedMap.get(e.id).push(e)
}
else {
groupedMap.set(e.id, [e])
}
}