Dec 02, 2021 06:50 AM
Hello everyone!
I am trying to get an array of unique items which are objects of two keys
{id: "record ID", name: "name of record"}
To filter out duplicate items I use rather complicated way. I define 3 arrays:
Code looks like this:
let d = [];
let u = [];
let v = [];
d = [{id:1, name:"a"},{id:3, name:"b"},{id:3, name:"b"}];
console.log(d);
u = [...new Set(d.map(d => d.id))];
v = [...new Set(d.map(d => d.name))];
d = [];
let m = 0;
while (m < u.length){ d[m] = {id:u[m],name:v[m]}; m++ }
console.log(d);
As you can see I am using a Set to filter out duplicates. Unfortunately, this works only for simpler arrays (or I do not know how to use it in my case). Is there any easier or brief way to do that? Any valuable suggestion is much appreciated.
Solved! Go to Solution.
Dec 03, 2021 08:18 AM
Hi @Andrey_Kovalev - I would also reach for Set
when trying to get a unique set of values, but Set
only works with primitive values or object references (but not actual objects). Here’s a method that doesn’t use Set
let array = [
{id:1, name:"a"},
{id:3, name:"b"},
{id:3, name:"b"},
{id:1, name:"a"},
{id:1, name:"a"},
];
const result = [];
const map = new Map();
for (let item of array) {
if(!map.has(item.id)){
map.set(item.id, true);
result.push(item);
}
}
console.log(result)
This uses Map
to note whether or not the loop has already seen a specific id. If not, then the current object is added to the result array; if it has been seen, then we move onto the next item in the array.
Dec 03, 2021 08:18 AM
Hi @Andrey_Kovalev - I would also reach for Set
when trying to get a unique set of values, but Set
only works with primitive values or object references (but not actual objects). Here’s a method that doesn’t use Set
let array = [
{id:1, name:"a"},
{id:3, name:"b"},
{id:3, name:"b"},
{id:1, name:"a"},
{id:1, name:"a"},
];
const result = [];
const map = new Map();
for (let item of array) {
if(!map.has(item.id)){
map.set(item.id, true);
result.push(item);
}
}
console.log(result)
This uses Map
to note whether or not the loop has already seen a specific id. If not, then the current object is added to the result array; if it has been seen, then we move onto the next item in the array.
Dec 05, 2021 07:36 AM
@JonathanBowen thank you for your solution. I will definetely try it.
Dec 05, 2021 10:12 AM
@JonathanBowen your solution is twice faster than mine. Thanks again for demonstrating how to use Maps. This was new to me.