0
Problem:
I’m trying to sort an array of boxes according to the tags so that the more compatible tags the more you’ll be in the first place.
tags = ['new', 'tech'];
boxes = [{
id: 1,
name: 'tech ipsum',
tags: ['watch', 'tech'],
},
{
id: 2,
name: 'apple ipsum',
tags: ['new', 'tech', 'apple'],
},
{
id: 3,
name: 'windows ipsum',
tags: ['tech', 'apple'],
},
];
boxes.map(box => {
console.log(box);
box.tags.includes(tags);
console.log(box.tags.includes(tags));
});
I’m trying to solve this problem by creating two loops and going through the tags and counting how many combinations are and then I save the index and sort at the end, but this is not an acceptable algorithm, it has some formula or algorithm name to help solve this problem?
This would be the expected result:
[{
id: 2,
name: 'apple ipsum',
tags: ['new', 'tech', 'apple'],
}, {
id: 3,
name: 'windows ipsum',
tags: ['tech', 'apple'],
}, {
id: 1,
name: 'tech ipsum',
tags: ['watch', 'tech'],
}]
Very good your answer! Only thing I would adjust is "newBoxes = boxes.Sort(...)" because, according to the documentation, the Sort method does not return a new array.
– Fábio Batista
My fault, it is not necessary to assign to a new variable. Removed! Thank you for the warning
– Keit Oliveira