![](/img/trans.png)
[英]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.