javascript - 过滤包含数组的对象数组
问题描述
这是我拥有的数组的一个较小版本,但它具有相同的结构
使用下面的 const arr,我想创建 2 个具有唯一值的新数组,这些数组按升序排序
const arr = [{
tags: ['f', 'b', 'd'],
weight: 7,
something: 'sdfsdf'
},
{
tags: ['a', 'b', 'c', 'd', 'e'],
weight: 6,
something: 'frddd'
},
{
tags: ['f', 'c', 'e', 'a'],
weight: 7,
something: 'ththh'
},
{
tags: ['a', 'c', 'g', 'e'],
weight: 5,
something: 'ghjghj'
}
];
const finalTags = [];
const finalWeight = [];
// TODO: find a better way to do this
arr.forEach(v => {
if (finalWeight.indexOf(v.weight) === -1) finalWeight.push(v.weight);
v.tags.forEach(val => {
if (finalTags.indexOf(val) === -1) finalTags.push(val);
});
});
// Ascending order
finalTags.sort();
finalWeight.sort();
我上面的作品,但似乎有点凌乱,如果有更好/更整洁的方式来做这件事
解决方案
一种解决方案是使用Array.reduce()创建两组,一组使用 ,tags
另一组使用weights
. 在此之后,您可以将它们转换sets
为arrays
并使用Array.sort():
const arr = [
{
tags: ['f', 'b', 'd'],
weight: 7,
something: 'sdfsdf'
},
{
tags: ['a', 'b', 'c', 'd', 'e'],
weight: 6,
something: 'frddd'
},
{
tags: ['f', 'c', 'e', 'a'],
weight: 7,
something: 'ththh'
},
{
tags: ['a', 'c', 'g', 'e'],
weight: 5,
something: 'ghjghj'
}
];
let res = arr.reduce((acc, {tags, weight}) =>
{
acc.tags = new Set([...acc.tags, ...tags]);
acc.weights.add(weight);
return acc;
}, {tags: new Set(), weights: new Set()});
let sortedWeigths = [...res.weights].sort();
let sortedTags = [...res.tags].sort((a, b) => a.localeCompare(b));
console.log("weights: ", sortedWeigths, "tags: ", sortedTags);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
推荐阅读
- c# - Trying to get injected service for seeding data in ASP.NET core MVC
- angular - Angular 8 加载外部 npm 包
- php - 如何将具有空格的字符串(两个单词)传递给href链接作为查询字符串
- netlify - How to hide folder path with `Netlify`?
- wordpress - How can I change how my WordPress theme displays categories? I want to display subcategories under parent category
- python - Unable to send e-mail using python
- google-cloud-dataflow - CombinePerKey not merging accumulators across multiple workers
- docker - Pod 卡在“CrashLoopBackOff”上,即使它应该进入 /bin/bash
- python - 在 Alpine Linux 中使用与 apk 一起安装的 Python 包
- html - Bootstrap 无法右对齐我的 DIV - 右拉不起作用