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 ?
CodePudding user response:
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;
CodePudding user response:
Basically I did 2 phases. First I group by category (at most 2 items per category), then I flatten it. I made it into a general function called group_by_at_most
var myArray = get_data();
var result = group_by_at_most(myArray, 'category', 2);
console.log(result);
function group_by_at_most(myArray, by, at_most) {
var obj = {}
myArray.forEach(function(item) {
if (!obj[item[by]]) {
obj[item[by]] = []
}
if (obj[item[by]].length < at_most) {
obj[item[by]].push(item);
}
})
var result = [];
for (var key in obj) {
var items = obj[key];
result.push(...items);
}
return result;
}
function get_data() {
return [{
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'
}
]
}
.as-console-wrapper {
max-height: 100% !important;
}