数组合并基于两个值

时间:2014-06-09 09:29:49

标签: javascript jquery arrays

我有一个像:

这样的数组
Name  Qty Price
happ   1   50
happ   1   50
happ   1   50
happ   2   10
app    1   50
app    1   50
app    1   50
app    2   10

我必须使用JavaScript / jquery转换和合并:

Name  Qty Price
 happ   3   50
 happ   2   10
 app    3   50
 app    2   10

基于相同的名称和价格

任何帮助都应该受到赞赏。

2 个答案:

答案 0 :(得分:2)

我喜欢这样的任务。它们并不困难,有助于将自己转变为工作状态。

// Sample data
arr = [{ name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'harr', qty: 1, price: 50 }];
result = {};

// Summarize array by one walk
arr.forEach(function(k) {
  if (!result[k.name + k.price]) {
    result[k.name + k.price] = k;
  } else {
    result[k.name + k.price].qty += k.qty;
  }
});

// convert object to array by one walk
var finalResult = [];
for (var key in result) { finalResult.push(result[key]) }

答案 1 :(得分:1)

此问题等同于SQL查询:

SELECT name, sum(qty), price 
FROM dataObject
GROUP BY name, price
ORDER BY sum(qty) DESC

您可以使用原生函数.reduce()汇总数据,然后.sort()qty排序:

<强> HTML

<div id="results"></div>

<强>的Javascript

// Sample data
arr = [{ name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 2, price: 10 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 2, price: 10 }];

var groupedObjects = arr.reduce(function(res, obj) {
    if (!((obj.name + obj.price) in res))
        res.__array.push(res[obj.name + obj.price] = obj);
    else {
        res[obj.name + obj.price].qty += obj.qty;        
    }
    return res;
}, {__array:[]}).__array
                .sort(function(a,b) { return b.qty - a.qty; });



// print results for testing
_.each(groupedObjects,function(obj){
    var output = '';
    _.each(obj,function(val,key){
        output += key+': '+val+'<br>';         
    });
    output += '<br>';
    $('#results').append(output);
});

<强>输出

name: happ
qty: 3
price: 50

name: app
qty: 3
price: 50

name: happ
qty: 2
price: 10

name: app
qty: 2
price: 1

Working Demo