Home >Web Front-end >JS Tutorial >JS+JSON creates array deduplication algorithm
This time I will bring you JS JSON to create an array deduplication algorithm. What are the precautions for JS JSON to create an array deduplication algorithm. The following is a practical case, let's take a look.
Requirement description: Remove items with the same paymode field in the JSON array and accumulate paymoney.
paylist:[{paymode:'1',payname:"现金",paymoney:"20"}, {paymode:'2',payname:"支付宝",paymoney:"50"},{paymode:'1',payname:"现金",paymoney:"40"}]
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; }
General JSON array deduplication
/* * 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; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to develop a custom library
##jquery dynamically adds click event step-by-step explanation
The above is the detailed content of JS+JSON creates array deduplication algorithm. For more information, please follow other related articles on the PHP Chinese website!