从对象数组中过滤唯一值

时间:2017-04-12 15:43:51

标签: javascript

如何使用Array.filter()返回带id的唯一name

我的场景与我研究的解决方案略有不同,因为我有一个对象数组。我找到的每个例子都包含一个单值的平面数组。



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 unique = data.filter(
function (x, i) {
   return data[i].id.indexOf(x.id) === i
});




提前致谢。

1 个答案:

答案 0 :(得分:13)

我认为forEach()更能实现您的目标:



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);
&#13;
&#13;
&#13;

如果您真的想使用filter(),请尝试以下方式:

&#13;
&#13;
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);
&#13;
&#13;
&#13;