16

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

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.

0

1 Answer 1

47

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

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:

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

Sign up to request clarification or add additional context in comments.

7 Comments

Yup, that's it ! I was going for a for loop, but I think filter is best.
I don't understand why SO jumps to conclusions so quickly re: with a duplicate answer remark. I had searched, but hadn't found the best solution for my scenario.
I think that forEach would be better since this approach does not actually use the filter function, since it does not return anything inside the function.
data = data.reduce((items, item) => items.find(x => x.name === item.name) ? [...items] : [...items, item], [])
@jinglesthula my bad, use just items in the first ternary branch
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.