假设我有2个JavaScript多维水果数组。
Array 1
-------------
Item, Count
Apple, 1
Apple, 1
Apple, 1
Orange, 1
Orange, 1
Orange, 1
Array 2
--------------
Item, Count
Apple, 1
Orange, 1
我想要一个新数组,其中数组2中的项目将从数组1中删除并一起添加。
Array Result
--------------
Item, Total
Apple, 2
Orange, 2
答案 0 :(得分:0)
var Array1 = [{Apple: 1},{Apple: 1},{Apple: 1},{Orange: 1},{Orange: 1},{Orange: 1}];
var Array2 = [{Apple: 1},{Orange: 1}];
var Result = Array2.reduce(function(res, item) {
return Object.keys(item).reduce(function(res, key) {
res[key] = res[key] || 0;
res[key] -= parseInt(item[key]);
return res
}, res);
}, Array1.reduce(function(res, item) {
return Object.keys(item).reduce(function(res, key) {
res[key] = res[key] || 0;
res[key] += parseInt(item[key]);
return res
}, res);
}, {}));
var Answer = Object.keys(Result).reduce(function(arr, key) {
var o = {};
o[key] = Result[key];
return arr.push(o) && arr;
}, []);
console.log(Answer);

或者,如果输入数据采用以下格式
var Array1 = [['Apple', 1],['Apple', 1],['Apple', 1],['Orange', 1],['Orange', 1],['Orange', 1]];
var Array2 = [['Apple', 1],['Orange', 1]];
var Result = Array2.reduce(function(res, item) {
var key = item[0], value = item[1];
res[key] = res[key] || 0;
res[key] -= parseInt(value);
return res;
}, Array1.reduce(function(res, item) {
var key = item[0], value = item[1];
res[key] = res[key] || 0;
res[key] += parseInt(value);
return res;
}, {}));
var Answer = Object.keys(Result).reduce(function(arr, key) {
return arr.push([key, Result[key]]) && arr;
}, []);
console.log(Answer);