skip to Main Content

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"
      }
   }
]

2

Answers


  1. Try this updated function

    function filterObject(data: any) {
      let hubs: {[key: string]: any} = {};
    
      data.forEach((item: any) => {
        const key = `${item.country}-${item.model}`;
    
        if (!hubs[key] || item.year > hubs[key].year) {
          hubs[key] = { country: item.country, model: item.model, year: item.year };
        }
      });
    
      let result = Object.values(hubs).map((hub) => {
        return { hub: { country: hub.country, model: hub.model } };
      });
    
      return result;
    }
    

    itz working as per your expectation.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search