Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter unique values from an array of objects [duplicate]

Tags:

javascript

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.

like image 935
bob.mazzo Avatar asked Apr 12 '17 15:04

bob.mazzo


People also ask

How do you filter out duplicates in array of objects?

To remove the duplicates from an array of objects: Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you get all unique values remove duplicates in a JavaScript array?

Method 2: Using array filter() method: The arr. filter() function is used to create a new array from existing array consisting of only those elements from the given array which satisfy a condition set by the argument function.


1 Answers

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);
like image 182
Mamun Avatar answered Oct 15 '22 17:10

Mamun