Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript and es6 filter array with unique key

I have a list in variable like:

var name_list = some_list

console.log(name_list)

Array[3]
   0: Object
       name: "Johny"
   1: Object
       name: "Monty"
   2: Object3:
      name: "Johny"

I want to get the list with non repetitive list. How can I do this ?

Update

I tried with this..

var unique_name = [ ...new Set(name_list.map(name => {
                return name.name
            }))]

It works fine but I want the object that are filtered unique according to name.

Any idea ??

like image 842
gamer Avatar asked Sep 01 '25 16:09

gamer


1 Answers

Another approach I don't see in here would be to use a Map

var name_list = [{name: "Johny"}, {name: "Monty"}, {name: "Johny"}];

// Make a mapping of name to object, then pullout objects.
var name_map = new Map(name_list.map(o => [o.name, o]));
var unique_names = [...name_map.values()];

Note, this will take the last object for each name instead of the first, but you could always do name_list.slice().reverse().map( instead of you need specifically the first object found.

like image 54
loganfsmyth Avatar answered Sep 06 '25 00:09

loganfsmyth