假设我们有一个像这样的对象数组-
const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}, {name: "Jack", age: "21"}];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组,并删除所有名称重复的对象。
因此,对于上述数组,输出应为-
const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}];
以下是代码-
const arr = [ {name: "Jack", age: "14"}, {name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}, {name: "Jack", age: "21"} ]; const removeDuplicate = arr => { const appeared = {}; for(let i = 0; i < arr.length; ){ if(!appeared.hasOwnProperty(arr[i].name)){ appeared[arr[i].name] = 1; i++; continue; }; arr.splice(i, 1); }; }; removeDuplicate(arr); console.log(arr);
输出结果
这将在控制台中产生以下输出-
[ { name: 'Jack', age: '14' }, { name: 'bob', age: '14' }, { name: 'sue', age: '21' }, { name: 'Jill', age: '16' } ]