[Vuejs]-How to not display duplicates from many objects in an Array

0๐Ÿ‘

โœ…

You can use computed property to make matches array unique.

For example:

  computed: {
    uniqueMatches () {
       return this.matches.map(item => {
         let households = Object.values(item.household)
         let relationships = households.map(item => item.relationship)
         const uniqueRelationships = [...new Set(relationships)]
         item.household = uniqueRelationships.reduce((acc, cur, idx) => {
            acc[idx] = {}
            acc[idx].relationship = cur
            return acc
          }, {})
          console.log(item)
         return item
       })
    }
  }

and then use uniqueMatches instead of matches in template

Demo in jsfiddle

0๐Ÿ‘

You could massage the data a bit and create a uniqueHouseholdMembers array property on each match in the matches array and then just print out those values:

matches.forEach(match => {
  let houseHolds = Object.values(match.household);

  match.uniqueHouseholdMembers = houseHolds.reduce((acc, household) => {
    // check if household member has already been added to our growing list
    let isUniqueRelationship = !acc.includes(household.relationship);

    // add household member if unique
    if (isUniqueRelationship) {
      acc.push(household.relationship);
    }

    return acc;
  }, []);
});

// output using the data you provided:
// match[0].uniqueHouseholdMembers -> ['brother']
// match[1].uniqueHouseholdMembers -> ['sister']

// and if you have a 3rd match entry with more household members:
// match[2].uniqueHouseholdMembers -> ['brother', 'father', 'stranger']

Leave a comment