ES6方式-通过键从嵌套数组中获取唯一值

Koa*_*Kid 5 javascript sorting filtering

努力提高我的 JS 能力。

是否有一种更清晰的方法可以从嵌套对象中按键从下面的数组中检索属性值,删除重复项并按字母顺序对它们进行排序?

这是我所拥有的:

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();
    },
Run Code Online (Sandbox Code Playgroud)

对象数组示例:

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

Run Code Online (Sandbox Code Playgroud)

预期输出应该是一个数组:

var array = ['a','b','c']
Run Code Online (Sandbox Code Playgroud)

Yev*_*kov 0

如果您需要简洁的内容,您可以这么简单:

const src = [{name:'hello',value:['c','b','d']},{name:'hello',value:['e','b','c']},{name:'hello',value:['f','a','e']}],

      result = [...new Set(src.flatMap(({value}) => value))].sort()

console.log(result)
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{min-height:100%;}
Run Code Online (Sandbox Code Playgroud)

如果您需要非常快的东西,您可以执行以下操作:

const src = [{name:'hello',value:['c','b','d']},{name:'hello',value:['e','b','c']},{name:'hello',value:['f','a','e']}],

      result = [...src.reduce((acc,{value}) => 
        (value.forEach(acc.add, acc), acc), new Set())].sort()

console.log(result)
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{Min-height:100%;}
Run Code Online (Sandbox Code Playgroud)