当前位置:网站首页>JS to determine the added and decreased elements of two arrays

JS to determine the added and decreased elements of two arrays

2022-06-23 07:27:00 Sister Chunfeng

One 、 Use scenarios

1、 Compare the two arrays to increase 、 Reduced elements ;

2、 In the actual project, when the current station sends data in array format to the background , You can compare new and old data first , Only changes are sent to the background each time . Increase transmission efficiency ;

Two 、 Code

/** *  Method name : *  Function is introduced : Returns an object that contains an array that is greater than the first array 、 Reduced data ( Applicable to the array after de duplication ) *  Parameters : * beforeArr: The previous array  * afterArr: The latter array  */
function compare(beforeArr,afterArr){
    
    let resObj = {
    
        add : [],
        del : []
       },
       cenObj = {
    };
   // hold beforeArr Array de reloading cenObj 
    for(let i=0;i<beforeArr.length;i++){
    
        cenObj[beforeArr[i]] = beforeArr[i];
    }
    // Traverse afterArr, Check whether its element is in cenObj in 
    for (let j=0;j<afterArr.length;j++){
    
        if (!cenObj[afterArr[j]]){
    
            resObj.add.push(afterArr[j]);
        }else {
    
            delete cenObj[afterArr[j]]
        }
    }
    for (k in cenObj){
    
        resObj.del.push(k);
    }
    return resObj;
}
var beArr = [1,2,3,4],
    afArr = [2,3,6];
compare(beArr,afArr)

3、 ... and 、 Running results :

 Insert picture description here

原网站

版权声明
本文为[Sister Chunfeng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230606053296.html