首页 > 解决方案 > 过滤包含数组的对象数组

问题描述

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

使用下面的 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();

我上面的作品,但似乎有点凌乱,如果有更好/更整洁的方式来做这件事

标签: javascriptarrayssortingecmascript-6

解决方案


一种解决方案是使用Array.reduce()创建两组,一组使用 ,tags另一组使用weights. 在此之后,您可以将它们转换setsarrays并使用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;}


推荐阅读