按属性删除数组重复项 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的对象数组 −
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' } ]