Home >Web Front-end >JS Tutorial >Detailed explanation of steps to implement JSON array deduplication using JS
This time I will bring you a detailed explanation of the steps to implement JSON array deduplication with JS. What are the precautions for JS to implement JSON array deduplication. 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:
Detailed explanation of the steps to build the Koa project
JS implementation of text font printing interface
vue-simplemde implements image drag and paste function (with code)
The above is the detailed content of Detailed explanation of steps to implement JSON array deduplication using JS. For more information, please follow other related articles on the PHP Chinese website!