Filtering unique values ββfrom an array of objects
How can I use Array.filter () to return unique id
with name
?
My scenario is slightly different from the solutions I 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.
+5
source to share
1 answer
I think the best way to achieve what you are looking for is: 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 try the following method: 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);
+12
source to share