Filtering an array of objects that contain arrays
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; }
One solution is to use Array.reduce() to create two sets, one with the tags
and other with the weights
. After this you can transform the sets
to arrays
and use Array.sort() on they:
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;}