window.onload = function () {
//测试数据
var WorkList = [
{ DistributorName: '上海01', ScanNumber: 10, DistributorCode: "w22222" },
{ DistributorName: '上海01', ScanNumber: 2, DistributorCode: "w22222" },
{ DistributorName: '上海01', ScanNumber: 1, DistributorCode: "w22222" },
{ DistributorName: '上海2', ScanNumber: 2, DistributorCode: "q111" },
{ DistributorName: '上海2', ScanNumber: 9, DistributorCode: "q111" },
{ DistributorName: '上海2', ScanNumber: 11, DistributorCode: "q111" },
{ DistributorName: '上海3', ScanNumber: 3, DistributorCode: "rt5" },
{ DistributorName: '上海3', ScanNumber: 2, DistributorCode: "rt5" },
{ DistributorName: '上海3', ScanNumber: 4, DistributorCode: "rt5" },
{ DistributorName: '上海3', ScanNumber: 4, DistributorCode: "rt5" },
{ DistributorName: '上海4', ScanNumber: 5, DistributorCode: "f432" },
{ DistributorName: '上海4', ScanNumber: 5, DistributorCode: "f432" },
{ DistributorName: '上海4', ScanNumber: 5, DistributorCode: "f432" },
{ DistributorName: '上海5', ScanNumber: 5, DistributorCode: "b432" },
{ DistributorName: '上海5', ScanNumber: 5, DistributorCode: "b432" },
{ DistributorName: '上海5', ScanNumber: 5, DistributorCode: "b432" },
{ DistributorName: '上海7', ScanNumber: 5, DistributorCode: "h001" },
];
var newList = addTableList(WorkList);
console.log(JSON.stringify(newList))
}
var list = [];
function addTableList(arr) {
arr.push([]);//确保最后一个数据有对比并返回其对比结果
var ScanNumber;
for (var i = 0; i < arr.length; i++) {
for (var j = i+1; j < arr.length; j++) {
if (arr[i].DistributorCode == arr[j].DistributorCode) {
//将相同编号的数据数量相加一起并返回数量和
ScanNumber = arr[i].ScanNumber + arr[j].ScanNumber;
arr[i].ScanNumber = ScanNumber;
} else {
//不相同编号,截取数据
list.push(arr[i]);//将重复的数据添加一条放到新的数组中
i = j;//重新给I赋值,取最后不同数据的下标值
ScanNumber = 0;//重新将数量赋值0
}
}
}
return list;
}
//第二种方法,参考
function addTableList(arry) {
var temp = {}; var data = [];
for (var i in arry) {
var key = arry[i].DistributorCode;
console.log(key)
if (temp[key]) {
temp[key].ScanNumber = parseInt(temp[key].ScanNumber) + parseInt(arry[i].ScanNumber);
temp[key].DistributorName = arry[i].DistributorName;
temp[key].DistributorCode = arry[i].DistributorCode;
} else {
temp[key] = {};
temp[key].ScanNumber = parseInt(arry[i].ScanNumber);
temp[key].DistributorName = arry[i].DistributorName;
temp[key].DistributorCode = arry[i].DistributorCode;
data.push(temp[key]);
}
}
console.log(JSON.stringify(data))
return data;
}