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

标签 javascript arrays sorting ecmascript-6

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

使用下面的 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/

相关文章:

Javascript 计算步数

javascript - nodejs 函数中的可选参数

javascript - useState 和 useEffect 有什么区别?

Objective-C setter 二维数组

javascript - jquery 排序函数和前置/插入之后?

python - 重组数组的数组并组合相同的项

Javascript 日期问题,时区不正确

arrays - 迭代变体数组

php - 分解数组的数据并创建新数组

java - HashMap字典顺序java如果值相同