繁体   English   中英

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

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

试图提高我的 JS 能力。

有没有一种更简洁的方法可以从嵌套的 object 中按键从下面的数组中检索属性值,删除重复项并按字母顺序排序?

这是我所拥有的:

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();
    },

object 的示例数组:

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

预计 output 应该是一个数组:

var array = ['a','b','c']

您可以只使用一个 Set,并将所有项目添加到其中:

 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() )

如果你需要简洁的东西,你可以 go 就这么简单:

 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)
 .as-console-wrapper{min-height:100%;}

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

 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)
 .as-console-wrapper{Min-height:100%;}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM