Home > Software engineering >  finding repeated value in objects inside an array in javascript
finding repeated value in objects inside an array in javascript

Time:08-31

have an array of data for example :

const array=[{ a:"cat"}, { a:"dog"}, { a:"dog"},{ a:"dog"}]

iterating over the array and looking for a logic to check the value of " a " to see if it is repeated or not, if repeated return only once otherwise return

CodePudding user response:

let values = new Set()
newArray = array.filter(obj => {
    if(values.has(obj.a)) return false;
    values.add(obj.a);
    return true;
  });

I would suggest, if you intend to use a as basically a key, using a Map or Object instead of an Array to hold data.

CodePudding user response:

You can try like this

const array=[{ a:"cat"}, { a:"dog"}, { a:"dog"},{ a:"dog"}]
const unique = array
     .map(e => e['a'])
     .map((e, i, final) => final.indexOf(e) === i && i)
     .filter(obj=> array[obj])
     .map(e => array[e].a);
     console.log(unique)

  • Related