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

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))
習慣沉默

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('谁重复了?');
    console.log('元素:', a); 
    console.log('下标:', b);
    console.groupEnd(); 
}

// 遍历 
arr.filter((item, idx, its) => {
    // 一旦发现有重复的元素就返回 true  (通过 its.some 注意他的两个参数 e 和 idx2)
    // 无重复的过滤掉  
    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;
}

// 简单数组去重
if (!key) {
    return Array.from(new Set(arr));
}

// 复杂数组去重
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!