Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 way - Get unique values from a nested array by key

trying to improve my JS chops.

Is there a cleaner way to retrieve the property value from the array below, by key, from a nested object, removing duplicates and sorting them alphabetically?

Here's what I have:

getObjectValues(array, key){

      var unique = [];
      
      array.forEach(function(item){
        item[key].forEach(function(value){
          if (unique.indexOf(value) < 0) {
            unique.push(value)
          }
        })
      });

      return unique.sort();
    },

example array of object:

[
  { name: 'hello', value: ['a','b','c']},
  { name: 'hello', value: ['a','b','c']},
  { name: 'hello', value: ['a','b','c']}
]

expected output should be an array:

var array = ['a','b','c']
like image 706
KoalaKid Avatar asked Nov 15 '22 08:11

KoalaKid


1 Answers

You could just use a Set, and add all the items to it:

let arr = [
  { name: 'hello', value: ['a','b','c']},
  { name: 'hello', value: ['a','b','c']},
  { name: 'hello', value: ['a','b','c']}
]

console.log(
    Array.from(
        new Set(
            arr.reduce(
                (carry, current) => [...carry, ...current.value],
                 []
            )
        )
    ).sort()
)
like image 178
dave Avatar answered Dec 10 '22 01:12

dave