Search code examples
javascriptloopsiteration

Javascript Loop over array of objects and get unique values


I have an array of car objects (carArray) and I want to loop over that array and fill a new array with the unique objects with only the type of CarA: 'Ford'.

const carArray = [
{carA:'Ford'},
{carA:'Ford'},
{carB:'GM'},
{carB:'GM'},
{carA:'Ford'},
{carA:'Ford'},
{carB:'GM'},
{carB:'Ford'},
]

Can someone tell me how I can do this?

Thank you so much for your time. regards, L


Solution

  • Try this

     let  newArray = [];
     carArray.forEach(function(car) {
       let arrayKey = Object.keys(car)[0]
       if (newArray.length > 0) {
           newArray.find(function (data) {
             if(!data.hasOwnProperty(Object.keys(data)[0])) { 
                newArray.push(car);
             }
           })
        }  else newArray.push(car)
     });