Home > Software design >  Getting distinct values from an array in VueJS while keeping multiple data elements
Getting distinct values from an array in VueJS while keeping multiple data elements

Time:03-21

I am new to VueJS and am having an issue getting distinct values out of an array. I have a data array with multiple columns. I'm attempting to get distinct values out to use them for checkboxes. The issue I'm running into is I can't seem to get both columns while still keeping the distinct ones. Any advice would be greatly appreciated.

Incoming data example:

const array = [{
    'name': 'Alpha',
    'id': 1,
    'note': 'asdfasdf'
  },
  {
    'name': 'Beta',
    'id': 2,
    'note': 'asdfasdf'
  },
  {
    'name': 'Alpha',
    'id': 1,
    'note': 'asdfasdf'
  }
  ]

What I'd like to be the output of the function:

const array = [{
    'name': 'Alpha',
    'id': 1
  },
  {
    'name': 'Beta',
    'id': 2
  }
  ]

How I would like to use the new array:

<v-checkbox
  v-for="(x,i) in array"
  :label="x.name"
  :value="x.id"
></v-checkbox>

I have tried the code below and I do get distinct values, but only one column.

[...new Set(this.array.map((x) => x.id))]

And when I try this I get both columns I want, but with duplicates.

[...new Set(this.array.map((x) => { return { name: x.name, id: x.id }}))]

CodePudding user response:

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[enter link description here][1] => 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}, {}));
  • Related