Home  >  Article  >  Web Front-end  >  How to implement deduplication algorithm in JSON array in JS

How to implement deduplication algorithm in JSON array in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-12 10:06:011958browse

This time I will show you how to implement the deduplication algorithm in JSON array with JS. What are the precautions for JS to implement the deduplication algorithm of JSON array? The following are Let’s take a look at practical cases.

Description of requirements: 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"}]
rrree

Universal JSON array deduplication

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;
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!

Recommended reading:

How to request local json data in vue configuration

pandas dataframe implements row selection and slicing operations

The above is the detailed content of How to implement deduplication algorithm in JSON array in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn