Javascript 从对象数组中过滤唯一值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43374112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:53:14  来源:igfitidea点击:

Filter unique values from an array of objects

javascript

提问by bob.mazzo

How can I use Array.filter() to return unique idwith name?

如何使用Array.filter()返回唯一idname

My scenario is slightly different than the solutions I have researched in that I have an array of objects. Every example I find contains a flat array of single values.

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

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
});

Thanks in advance.

提前致谢。

回答by Mamun

I think forEach()is better to achieve what you are looking for:

我认为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);

If you really want to use filter()try the following way:

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

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);