【发布时间】:2019-07-30 02:53:55
【问题描述】:
这是我拥有的数组的较小版本,但结构相同
使用下面的 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();
我上面的作品,但似乎有点凌乱,如果有更好/更整洁的方式来做这件事,我会徘徊
【问题讨论】:
-
codereview.stackexchange.com 会不会更好?
标签: javascript arrays sorting ecmascript-6