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
Following the voice in heart.
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
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'}]
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);
// 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;
}