Фильтрация массива объектов, содержащих массивы - PullRequest
6 голосов
/ 08 марта 2019

Это меньшая версия массива, которая у меня есть, но она имеет такую ​​же структуру

с 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();

то, что у меня есть выше, работает, но кажется немного грязным и блуждает, если есть способ лучше / опрятнее сделать это

Ответы [ 3 ]

2 голосов
/ 08 марта 2019

Одним из решений является использование Array.reduce () для создания двух наборов, один с tags, а другой с weights.После этого вы можете преобразовать sets в arrays и использовать 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;}
2 голосов
/ 08 марта 2019

Вы можете использовать Array.prototype.reduce () в сочетании с Установить , чтобы получить объект с отсортированными массивами {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; }
0 голосов
/ 08 марта 2019

Вы можете использовать следующий код.Это в основном разделяет arr на finalTags и finalWeights.

.flat() выравнивает массив ([1, [2, [3]]] станет [1, 2, 3])

finalTags.filter((item, index) => finalTags.indexOf(item) >= index).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 finalTags = arr.map(e => e.tags);
finalTags = finalTags.flat();
finalTags = finalTags.filter((item, index) => finalTags.indexOf(item) >= index).sort();

let finalWeight = arr.map(e => e.weight);
finalWeight = finalWeight.filter((item, index) => finalWeight.indexOf(item) >= index).sort();

console.log(finalTags);
console.log(finalWeight);

Источники:

Удаление дубликатов: https://gomakethings.com/removing-duplicates-from-an-array-with-vanilla-javascript/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...