Home > Blockchain >  JQuery Javascript Filtering Array By Latest Distinct Key
JQuery Javascript Filtering Array By Latest Distinct Key

Time:01-08

Thank you in advance for any help/advice.

I have an array object shown below.

{
    "DogName": "Max",
    "DogBreed": "GermanShepherd"
},
{
    "DogName": "Blitz",
    "DogBreed": "GoldRet"
},
{
    "DogName": "Max",
    "DogBreed": "Shitzu"
}

I am looking to filter this array to only show distinct values based on the last entry "DogName".

Therefore, the resulting array would look like this

{
    "DogName": "Blitz",
    "DogBreed": "GoldRet"
},
{
    "DogName": "Max",
    "DogBreed": "Shitzu"
}

Been trying for an hour with the foreach / inarray functions but not having much luck.

Your time is appreciated - thank you.

CodePudding user response:

Looking for a one-liner?

// Your dogs array
const dogs = [
{
    DogName: "Max",
    DogBreed: "GermanShepherd"
},
{
    DogName: "Blitz",
    DogBreed: "GoldRet"
},
{
    DogName: "Max",
    DogBreed: "Shitzu"
}];

// Use a Map to store unique dog objects by your desired key (e.g. DogName)
const filteredDogs = [...new Map(dogs.map(dog => [dog["DogName"], dog])).values()];

Hope it works!

  • Related