0

I have an array of objects in javascript, I am creating a new array from it but only with some properties. What I need is to filter the unique objects and eliminate the repeated ones, I'm trying to do it in the same function but I don't know if it's possible

This is the array:

let filters = [
  {
     "model":"audi",
     "year":2012,
     "country":"spain"
  },
  {
    "model":"bmw",
    "year":2013,
    "country":"italy"
  },
  {
    "model":"audi",
    "year":2020,
    "country":"spain"
  }
]

This is the function:

function filterObject(data: any) {
  let result = data.map((item: any) => {
    return {
      hub: {
        country: item.country,
        model: item.model
      }
    }
  })
  return result

}

This is what I get:

[
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   },
   {
      "hub":{
         "country":"italy",
         "model":"bmw"
      }
   },
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   }
]

This is what I need:

[
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   },
   {
      "hub":{
         "country":"italy",
         "model":"bmw"
      }
   }
]
element
  • 49
  • 5
  • @pilchard I've been reviewing those answers, but I can't find anything easy to adapt, what I need is something more generic to be able to take advantage of it in any array of objects, but I'm still trying with some example of that question – element Apr 05 '23 at 17:04
  • The accepted answer is extremely easy to adapt by simply passing an array of keys to construct the composite key from. Otherwise see [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) and the duplicate it's closed for for generic options you can pass to `filter()` – pilchard Apr 05 '23 at 17:21
  • 2
    example of a generic `unique` based on the duplicate: [jsfiddle](https://jsfiddle.net/q6t1f7bj/) (you could update the answer to use a `Set` instead of null object) – pilchard Apr 05 '23 at 17:29

1 Answers1

0

You can use Map to ensure only unique items:

function filterObject(data:any) {
  const uniqueObjects:any = [];
  const uniqueMap = new Map();

  data.forEach((item:any) => {
    const key = item.model + item.country;
    if (!uniqueMap.has(key)) {
      uniqueMap.set(key, true);
      uniqueObjects.push({
        hub: {
          country: item.country,
          model: item.model
        }
      });
    }
  });

  return uniqueObjects;
}

Playground

protob
  • 3,317
  • 1
  • 8
  • 19