I have an array like this :
JavaScript
x
28
28
1
const myArray = [
2
{
3
title: 'title',
4
category: 'genetic-diseases'
5
},
6
{
7
title: 'title',
8
category: 'genetic-disorders'
9
},
10
{ title: 'title', category: 'genetic-disorders' },
11
{
12
title: 'title',
13
category: 'genetic-disorders'
14
},
15
{
16
title: 'title',
17
category: 'genetic-mutation'
18
},
19
{
20
title: 'title',
21
category: 'genetic-mutation'
22
},
23
{
24
title: 'title',
25
category: 'genetic-mutation'
26
}
27
]
28
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 :
JavaScript
1
20
20
1
const myArray = [
2
{
3
title: 'title',
4
category: 'genetic-diseases'
5
},
6
{ title: 'title', category: 'genetic-disorders' },
7
{
8
title: 'title',
9
category: 'genetic-disorders'
10
},
11
{
12
title: 'title',
13
category: 'genetic-mutation'
14
},
15
{
16
title: 'title',
17
category: 'genetic-mutation'
18
}
19
]
20
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
JavaScript
1
45
45
1
const myArray = [
2
{
3
title: 'title',
4
category: 'genetic-diseases'
5
},
6
{
7
title: 'title',
8
category: 'genetic-disorders'
9
},
10
{ title: 'title', category: 'genetic-disorders' },
11
{
12
title: 'title',
13
category: 'genetic-disorders'
14
},
15
{
16
title: 'title',
17
category: 'genetic-mutation'
18
},
19
{
20
title: 'title',
21
category: 'genetic-mutation'
22
},
23
{
24
title: 'title',
25
category: 'genetic-mutation'
26
}
27
];
28
29
var categoryQuantities = {}; //counts how many objects from each category entered the filtered array
30
var filteredArray = []; //array with first 2 objects from each categoty
31
for (var obj of myArray) {
32
var category = obj.category;
33
if (category in categoryQuantities) {
34
categoryQuantities[category]++;
35
} else {
36
categoryQuantities[category] = 1;
37
}
38
39
if (categoryQuantities[category] <= 2) {
40
filteredArray.push(obj);
41
}
42
}
43
44
console.log(filteredArray);
45
The final array is in ‘filteredArray’. The original array is not changed, so you may want to do the following:
JavaScript
1
2
1
myArray = filteredArray;
2