JavaScript对数组中的项目进行排序和分组 [英] JavaScript sorting and grouping items in array
问题描述
我正在尝试在JavaScript中进行一些映射.我要尝试做的是尝试检查datasetarr
中是否存在arr
中的类型,如果存在,则获取datasetarr
中的索引并增加该索引的数量.如果不存在,则在datasetarr
中添加一个新条目.这是我的代码:
I am trying to do some mapping in JavaScript. What I am trying to do is I am trying to check if the type from arr
exists in datasetarr
, if existed, I get the index in datasetarr
and increment the quantity of that index. If not exists, I add in a new entry in datasetarr
. Here is my code:
var datasetarr = [];
var pos;
for(var i = 0; i < arr.length; i++){
console.log('unsorted ' + arr[i].type + ' ' + arr[i].quantity);
if(datasetarr.indexOf(arr[i].type) > -1){
pos = datasetarr.indexOf(arr[i].type);
datasetarr[pos].quantity += arr[i].quantity;
}else{
datasetarr.push({type: arr[i].type, quantity: arr[i].quantity});
}
}
for(var i = 0; i < datasetarr.length; i++){
console.log('sorted ' + datasetarr[i].type + ' ' + datasetarr[i].quantity);
}
输出应为:
kitchen appliance 20
home entertainment 8
batteries & lightings 4
home appliance 12
然后,我可以获取每种的类型和数量并存储到数组中,以便用图表进行绘制.
Then, I can get the type and quantity each and store into array for me to plot with chart.
但是,使用上面的代码,我得到的东西与未排序的东西完全相同.有什么想法我的逻辑哪一部分出错了吗?
However, with my code above, the things that I am getting is exactly the same as the unsorted one. Any ideas which part of my logic went wrong?
推荐答案
使用对象进行分组.
var categories = {};
function incrementBy(category, value) {
if (!categories[category]) {
categories[category] = 0;
}
categories[category] += value;
}
var datasetarr = [];
var pos;
for(var i = 0; i < arr.length; i++){
console.log('unsorted ' + arr[i].type + ' ' + arr[i].quantity);
incrementBy(arr[i].type, arr[i].quantity)
}
for(var category in categories){
console.log('sorted ' + category + ' ' + categories[category]);
}
您可以根据需要分解对象,将其分解为数组,然后根据需要对其进行排序.
You can decompose the object if needed, through it into an array and sort it if required.
一个更简洁的示例,它可能使您更好地遵循:
A little bit cleaner example, which might let you follow along a little bite better:
var arr = [{type: 'kitchen appliance', quantity: 2},
{type: 'home entertainment', quantity: 2},
{type: 'home entertainment', quantity: 3},
{type: 'batteries & lightings', quantity: 2},
{type: 'home entertainment', quantity: 2},
{type: 'home appliance', quantity: 5},
{type: 'kitchen appliance', quantity: 4},
{type: 'kitchen appliance', quantity: 5},
{type: 'kitchen appliance', quantity: 3},
{type: 'kitchen appliance', quantity: 4},
{type: 'kitchen appliance', quantity: 1},
{type: 'home entertainment', quantity: 1},
{type: 'home appliance', quantity: 5},
{type: 'batteries & lightings', quantity: 2},
{type: 'kitchen appliance', quantity: 2},
{type: 'home appliance', quantity: 2}];
function group(array) {
var categories = {};
function incrementBy(category, value) {
if (!categories[category]) {
categories[category] = 0;
}
categories[category] += value;
}
array.forEach(function (value, index, arr) {
incrementBy(value.type, value.quantity)
});
return categories;
}
function print(categories) {
for (var category in categories) {
console.log('%s: %s', category, categories[category]);
}
}
print(group(arr));
以下是group
的解决方案,它隐藏了分组,因此可以保存您自己的实现:
Here a solution of of group
hiding the grouping, which than can hold your own implementation:
function group(array) {
var categories = {};
function incrementBy(object) {
var category = categories[object.type];
if (!category) {
category = categories[object.type] = {};
}
var subCategory = category[object.subType];
if (!subCategory) {
subCategory = category[object.subType] = {};
}
subCategory += object.value;
}
array.forEach(function (value, index, arr) {
incrementBy(value, value.quantity)
});
return categories;
}
根据您的用例,您还可以展平结构:
Depending on your use case, you could also flatten the structure:
function incrementBy(object) {
var key = [object.type, object.subType].join('/');
var category = categories[key];
if (!category) {
category = categories[key] = {};
}
subCategory += object.value;
}
但是放置各种地图可能很有意义:
But it might make sense to have various maps in place:
function groupings(array) {
var groupings = {
types: {},
subTypes: {},
paths: {}
};
function incrementBy(object) {
var category = groupings['types'][object.type];
if (!category) {
category = groupings['types'][object.type] = {};
}
category += object.value;
var subCategory = groupings['subTypes'][object.subType];
if (!subCategory) {
subCategory = groupings['subTypes'][object.subType] = {};
}
subCategory += object.value;
var key = [object.type, object.subType].join('/');
var path = groupings['paths'][key];
if (!path) {
path = groupings['paths'][key] = {};
}
path += object.value;
}
array.forEach(function (value, index, arr) {
incrementBy(value, value.quantity)
});
return categories;
}
为避免聚合时信息丢失,您可以简单地创建一个更复杂的数据结构:
To avoid information loss on aggregations, you could simply create a more complex data structure:
function groupByAndSumBy(data, groupByProperty, sumByProperty) {
var accumulator = {};
data.forEach(function(object, index, array) {
var localAcc = accumulator[groupByProperty]
= accumulator[groupByProperty] || { items: [] };
localAcc[sumByProperty]
= (localAcc[sumByProperty] || 0) + object[sumByProperty];
localAcc.items.push(object);
});
return accumulator;
}
function groupByMerchantNameAndSumByTotalSales(data) {
return groupByAndSumBy(data, 'merchantName', 'totalSales');
}
这将创建一个聚合,其中还包含输入数组的子集,使您可以更详细地查看数据.
This creates an aggregation which also contains the subset of the input array, which allows you a more detailed view on the data.
这篇关于JavaScript对数组中的项目进行排序和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!