I have an array like this :
const myArray = [
{
title: 'title',
category: 'genetic-diseases'
},
{
title: 'title',
category: 'genetic-disorders'
},
{ title: 'title', category: 'genetic-disorders' },
{
title: 'title',
category: 'genetic-disorders'
},
{
title: 'title',
category: 'genetic-mutation'
},
{
title: 'title',
category: 'genetic-mutation'
},
{
title: 'title',
category: 'genetic-mutation'
}
]
I only want two of each of category object in the array and remove the rest If the number of objects of that category is over 2 and get something like this :
const myArray = [
{
title: 'title',
category: 'genetic-diseases'
},
{ title: 'title', category: 'genetic-disorders' },
{
title: 'title',
category: 'genetic-disorders'
},
{
title: 'title',
category: 'genetic-mutation'
},
{
title: 'title',
category: 'genetic-mutation'
}
]
How can I remove the rest of the objects of a specific category If the number of those objects in the array is over 2 ?
Advertisement
Answer
const myArray = [
{
title: 'title',
category: 'genetic-diseases'
},
{
title: 'title',
category: 'genetic-disorders'
},
{ title: 'title', category: 'genetic-disorders' },
{
title: 'title',
category: 'genetic-disorders'
},
{
title: 'title',
category: 'genetic-mutation'
},
{
title: 'title',
category: 'genetic-mutation'
},
{
title: 'title',
category: 'genetic-mutation'
}
];
var categoryQuantities = {}; //counts how many objects from each category entered the filtered array
var filteredArray = []; //array with first 2 objects from each categoty
for (var obj of myArray) {
var category = obj.category;
if (category in categoryQuantities) {
categoryQuantities[category]++;
} else {
categoryQuantities[category] = 1;
}
if (categoryQuantities[category] <= 2) {
filteredArray.push(obj);
}
}
console.log(filteredArray);
The final array is in ‘filteredArray’. The original array is not changed, so you may want to do the following:
myArray = filteredArray;