Filter unique values from an array of objects
本问题已经有最佳答案,请猛点这里访问。
如何使用array.filter()返回带有
我的方案与我研究过的解决方案稍有不同,因为我有一系列对象。我找到的每个示例都包含一个单一值的平面数组。
1 2 3 4 5 6 7 8 9 | data=[ {id: 555, name:"Sales", person:"Jordan" }, {id: 555, name:"Sales", person:"Bob" }, {id: 555, name:"Sales", person:"John" }, {id: 777, name:"Accounts Payable", person:"Rhoda" }, {id: 777, name:"Accounts Payable", person:"Harry" }, {id: 888, name:"IT", person:"Joe" }, {id: 888, name:"IT", person:"Jake" }, ]; |
1 2 3 4 | var unique = data.filter( function (x, i) { return data[i].id.indexOf(x.id) === i }); |
事先谢谢。
我认为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var data=[ {id: 555, name:"Sales", person:"Jordan" }, {id: 555, name:"Sales", person:"Bob" }, {id: 555, name:"Sales", person:"John" }, {id: 777, name:"Accounts Payable", person:"Rhoda" }, {id: 777, name:"Accounts Payable", person:"Harry" }, {id: 888, name:"IT", person:"Joe" }, {id: 888, name:"IT", person:"Jake" }, ]; var resArr = []; data.forEach(function(item){ var i = resArr.findIndex(x => x.name == item.name); if(i <= -1){ resArr.push({id: item.id, name: item.name}); } }); console.log(resArr); |
如果您真的想使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var data=[ {id: 555, name:"Sales", person:"Jordan" }, {id: 555, name:"Sales", person:"Bob" }, {id: 555, name:"Sales", person:"John" }, {id: 777, name:"Accounts Payable", person:"Rhoda" }, {id: 777, name:"Accounts Payable", person:"Harry" }, {id: 888, name:"IT", person:"Joe" }, {id: 888, name:"IT", person:"Jake" }, ]; var resArr = []; data.filter(function(item){ var i = resArr.findIndex(x => x.name == item.name); if(i <= -1){ resArr.push({id: item.id, name: item.name}); } return null; }); console.log(resArr); |