javascript - js determines whether an array is repeated
typecho2017-07-05 10:57:12
0
5
1090
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
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;
}
// 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;
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
Written on a whim. . . Not sure if all requirements are met. . . Haha
Method 1:
Method 2:
temp.indexOf ( arr[i].name ) = -1;
res.push(arr[i]);
There are many methods for deduplicating arrays, and you can have a better method
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.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 recordScreenShot
// 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) {
}