Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique array of objects filtering by object key? [duplicate]

i have an array of objects. Objects contain information about cities and their geometric info. here is my array

> [ {country: "AM", name: "Abovyan", lat: 40.27368, lng: 44.63348},
> {country: "AM", name: "Abovyan", lat: 40.04851, lng: 44.54742},
> {country: "AM", name: "Kapan", lat: 39.20755, lng: 46.4057} ]

As you can see i have 2 objects with the same name (e.g Abovyan) but their geometric info is different. This array i get from some API and i want to filter it . How can i filter it to have only one object with certain key/value , in this case with name ?

I would like to get a filtered array like this `

[ {country: "AM", name: "Abovyan", lat: 40.27368, lng: 44.63348},
  {country: "AM", name: "Kapan", lat: 39.20755, lng: 46.4057} ]
like image 369
Norayr Ghukasyan Avatar asked Sep 11 '25 21:09

Norayr Ghukasyan


1 Answers

Here we build an object from the non-duplicate items using the .name property as the object key. When we’re done we take the value array from that object.

var data = [ your data ];

var out = Object.values(
  data.reduce( (c, e) => {
    if (!c[e.name]) c[e.name] = e;
    return c;
  }, {})
);
like image 178
James Avatar answered Sep 13 '25 09:09

James