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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With