[英]Get common data from multiple arrays of object that containing a unique id and nested array using javascript 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 就這么簡單:
Set
去除重復項Array.prototype.flatMap()
(略帶解構賦值)將value
項從所有對象中提取到單個數組中 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%;}
如果您需要非常快的東西,您可以執行以下操作:
Array.prototype.reduce()
將您的數組轉換為一Set
唯一記錄(使用Array.prototype.forEach
遍歷value
項並執行Set.prototype.add()
)Set
傳播到數組和.sort()
中 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.