这是我拥有的一个较小版本的数组,但其结构相同
使用下面的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();
我上面的代码可以工作,但看起来有些混乱,我想知道是否有更好/更整洁的方法来做到这一点。