亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - js determines whether an array is repeated
typecho
typecho 2017-07-05 10:57:12
0
5
1206

How does js determine that there are duplicate values ??in an array object, and delete the duplicate values ??and keep only one
For example, var arr = [{name:'a'},{name:'b'}, {name:'c'},{name:'d'},{name:'a'}] How to compare

typecho
typecho

Following the voice in heart.

reply all(5)
伊謝爾倫

You can find it with a double for loop, compare the first one with the following ones, delete them if they are repeated, search from the second one, compare them backwards, and delete them if they are repeated

const del = (arr) => {
    for( let i=0;i<arr.length;i++) {
        for(let j=i+1;j<arr.length;j++) {
            if (arr[i].id==arr[j].id) {
                arr.splice(j,1);
                i--;
            }
        }
    }
    return arr;
}
伊謝爾倫

Written on a whim. . . Not sure if all requirements are met. . . Haha

Method 1:

const del = (arr)=>{
  let map = [];
  for(let i = 0; i < arr.length; i++) {
    let key = JSON.stringify(arr[i]);
    if(map.includes(key)) {
        arr.splice(i, 1);
        i--;
    } else {
        map.push(key);
    }
  }

  return arr;
}

Method 2:

const del = arr=>Array.from(new Set(arr.map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a))
習(xí)慣沉默

temp.indexOf ( arr[i].name ) = -1;

res.push(arr[i]);

There are many methods for deduplicating arrays, and you can have a better method

ringa_lee

Raw materials

arr is a one-dimensional array and the elements are objects. The content to be processed is the name attribute under the object.

var arr = [{name:'a'},{name:'b'},{name:'c'},{name:'d'},{name:'a'}]

Processing ideas

Traverse them, and then traverse them again based on each traversed item arr Compare them one by one. If duplicates are found, leave a record

var logger = (a, b) => {
    console.group('誰重復(fù)了?');
    console.log('元素:', a); 
    console.log('下標(biāo):', b);
    console.groupEnd(); 
}

// 遍歷 
arr.filter((item, idx, its) => {
    // 一旦發(fā)現(xiàn)有重復(fù)的元素就返回 true  (通過 its.some 注意他的兩個參數(shù) e 和 idx2)
    // 無重復(fù)的過濾掉  
    return its.some((e, idx2) => {
        return (e.name === item.name && idx2 !== idx); 
    });
}).forEach(logger); 

ScreenShot

我想大聲告訴你

// Array deduplication
// A key means complex array deduplication, which is based on the attribute key of the object in the array
function arrUniq(arr, key) {

if (!Array.isArray(arr) || arr.length < 2) {
    return arr;
}

// 簡單數(shù)組去重
if (!key) {
    return Array.from(new Set(arr));
}

// 復(fù)雜數(shù)組去重
var obj = {},
    res = [];

arr.forEach((item) => {
    if (!obj[item[key]]) {
        res.push(item);
        obj[item[key]] = true;
    }
});

return res;

}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template