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)
如果您需要简洁的内容,您可以这么简单:
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)Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{min-height:100%;}Run Code Online (Sandbox Code Playgroud)
如果您需要非常快的东西,您可以执行以下操作:
Array.prototype.reduce()将数组转换为Set唯一记录(使用 和循环遍历value项目)Array.prototype.forEachSet.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)Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{Min-height:100%;}Run Code Online (Sandbox Code Playgroud)