JS实现的JSON数组去重算法示例
网络 2018-05-11 1791
本文实例讲述了JS实现的JSON数组去重算法。分享给大家供大家参考,具体如下:
需求描述:去除JSON数组中paymode字段相同的项,并将paymoney累加。
1 2 | paylist:[{paymode:'1',payname:"现金",paymoney:"20"}, {paymode:'2',payname:"支付宝",paymoney:"50"},{paymode:'1',payname:"现金",paymoney:"40"}] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function UniquePay(paylist){ var payArr = [paylist[0]]; for(var i = 1; i < paylist.length; i++){ var payItem = paylist[i]; var repeat = false; for (var j = 0; j < payArr.length; j++) { if (payItem.paymode == payArr[j].paymode) { payArr[j].paymoney = parseFloat(payArr[j].paymoney)+parseFloat(payItem.paymoney); repeat = true; break; } } if (!repeat) { payArr.push(payItem); } } return payArr; } |
通用的JSON数组去重
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /* * JSON数组去重 * @param: [array] json Array * @param: [string] 唯一的key名,根据此键名进行去重 */ function uniqueArray(array, key){ var result = [array[0]]; for(var i = 1; i < array.length; i++){ var item = array[i]; var repeat = false; for (var j = 0; j < result.length; j++) { if (item[key] == result[j][key]) { repeat = true; break; } } if (!repeat) { result.push(item); } } return result; } |
下一篇:应收账款的作用是什么?