[Vuejs]-Getting distinct values from an array in VueJS while keeping multiple data elements

3👍

If these records are considered distinct based on id, you’re almost there: Just take the unique ids you found by putting them into a set, then find the first entry in the original array for each unique id:

const array = [...]

const ids = [...new Set(array.map(x => x.id))]; // your code from above
// ids = [ 1, 2 ]

const distinct = ids.map(id => array.find(x => x.id === id));
// distinct =
// [
//   { name: 'Alpha', id: 1, note: 'asdfasdf' },
//   { name: 'Beta', id: 2, note: 'asdfasdf' }
// ]

You could also reduce the array into an object to eliminate duplicates based on id, and then take the values of that object to get the associated entries:

const array = [...]
const distinct = Object.values(
    array.reduce((o, a) => { o[a.id] = a; return o}, {}));

Leave a comment