簡體   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