Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering an array of objects that contain arrays

This is a smaller version of the array i have but it has the same structure

with const arr below, i want to create 2 new arrays with unique values that are sorted in ascending order

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

what i have above works, but seems a bit messy and was wandering if there was a better/tidier way of doing this

like image 947
ace2case Avatar asked Mar 08 '19 05:03

ace2case


People also ask

How do you filter nested array of objects?

How do you filter nested array of objects? The filter() method creates a new array with all elements that pass the test implemented by the provided function. Approach 1: This approach uses filter() method to filter the nested object in JavaScript.

Can you filter an array?

The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.

Can filter be used on objects?

Unfortunately, JavaScript objects don't have a filter() function. But that doesn't mean you can't use filter() to filter objects, you just need to be able to iterate over an object and convert the object into an array using Object. entries() .


1 Answers

You can use Array.prototype.reduce() combined with Set in order to get an object with the sorted arrays {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; }
like image 106
Yosvel Quintero Arguelles Avatar answered Nov 15 '22 03:11

Yosvel Quintero Arguelles