尝试在 JavaScript 中对数组项进行排序和分组时,我遇到了一些麻烦。这是示例输入:
var arr = [
{merchantName: '', branchName: 'e', branchAddress: '', total: 10.5},
];
我想要实现的输出:
var arr = [
{merchantName: '', branchName: '', branchAddress: '', total: 10.5},
];
我想按 branchName
对它进行排序,例如对相同的 branchName
求和,然后同时绑定(bind)所有其他属性,例如 merchantName
和 branchAddress
连在一起,这样我就可以像这样访问它们:
for(var i = 0; i < arr.length; i++){
console.log(arr[i].merchantName + ' ' + arr[i].branchName + ' ' + arr[i].branchAddress + ' ' + arr[i].total);
}
我什至不知道如何开始它。有什么想法可以实现吗?
最佳答案
下面是我的做法:
根据
branchName
属性将数组分组到hashmap
- 计算总数。从
hashmap
中取出数组并排序
请看下面的演示:
var arr = [
{merchantName: 'Giant', branchName: 'Giant Marine', branchAddress: 'Terrace 56 Branch Blk 56 Marine Terrace #01-259/261 Singapore 440056', total: 10.5},
{merchantName: 'Ntuc', branchName: 'Ntuc Zhongshan Mall Branch', branchAddress: ' Zhongshan Mall Balestier #02-01, 20 Ah Hood Road, 329984', total: 12.149999999999999},
{merchantName: 'Giant', branchName: 'Giant Kim Keat 260 Branch', branchAddress: ' Blk 260 Kim Keat Avenue #01-01 Singapore 310260', total: 5.1},
{merchantName: 'Ntuc', branchName: 'Ntuc Scotts Square Branch', branchAddress: ' Scotts Square #B1-03 To 07 & #B1-10, 6 Scotts Road, 228209', total: 4},
{merchantName: 'Ntuc', branchName: 'Ntuc Zhongshan Mall Branch', branchAddress: ' Zhongshan Mall Balestier #02-01, 20 Ah Hood Road, 329984', total: 4},
{merchantName: 'Ntuc', branchName: 'Ntuc Zhongshan Mall Branch', branchAddress: ' Zhongshan Mall Balestier #02-01, 20 Ah Hood Road, 329984', total: 8}
];
// create a hashmap
var hash = arr.reduce(function(p,c){
if(!p[c.branchName])
p[c.branchName] = c;
else
p[c.branchName].total += c.total;
return p;
}, Object.create(null))
// now extract the result and sort them
var result = Object.keys(hash).map(function(e){
return hash[e];
}).sort(function(a,b){
return a.branchName - b.branchName;
});
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
关于JavaScript 数组排序通过对相同元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45450576/