gpt4 book ai didi

javascript - 过滤包含数组的对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:22 26 4
gpt4 key购买 nike

这是我拥有的数组的较小版本,但它具有相同的结构

使用下面的 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.prototype.reduce()结合 Set为了获得具有排序数组的对象 {tags: [], weights: []}:

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 obj = arr.reduce((a, {tags, weight}) => {
a.tags = [...new Set(a.tags.concat(tags))];
a.weights = [...new Set(a.weights.concat(weight))];
return a;
}, {tags: [], weights: []});

// final result i want
console.log('finalTags:', obj.tags.sort()); // ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
console.log('finalWeight:', obj.weights.sort()); // [5, 6, 7];
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤包含数组的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55057025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com