Search code examples
javascriptfiltervuexpushreduce

How to get unique array of objects filtering by object key Vuex?


I'm expecting to obtain a new array of ojects with a none repeatable key value trip_class. But I'm getting still 30 object items instead of a single one or two. Using computed initial array of objects Vuex.

From this :

[
    {name: 'john', trip_class: 0, lastname: 'lastname'}, 
    {name: 'Don', trip_class: 1, lastname: 'lastname'},
    {name: 'Joshua', trip_class: 1, lastname: 'lastname'},
    {name: 'Mary', trip_class: 2, lastname: 'lastname'}
]

I'd like to obtain this :

[
    {name: 'john', trip_class: 0, lastname: 'lastname'}, 
    {name: 'Don', trip_class: 1, lastname: 'lastname'},
    {name: 'Mary', trip_class: 2, lastname: 'lastname'}
]
    computed: {
            flights() {
              return this.$store.getters.getFlights;
            },
            flightsClasses() {
              console.log(this.flights)    // returns an array of objects
              let flightsClasses = this.flights 
                flightsClasses.reduce((acc, obj)=>{
                  var exist = acc.find((flightClass) => obj.trip_class === flightClass );
                  if(!exist){
                    acc.push(obj);
                  }
                  return acc;
                },[]);

              console.log('flightsClasses',flightsClasses)    // returns repeatable items array
              return flightsClasses
            },

Solution

  • Does this fix it?

    acc.find((flightClass) => obj.trip_class === flightClass.trip_class );