I have sorted array of objects:
const arr = [
{
"persentage": "30",
"value": "123"
},
{
"persentage": "27",
"value": "345"
},
{
"persentage": "2",
"value": "232"
},
{
"persentage": "2",
"value": "343"
},
{
"persentage": "9",
"value": "4334"
},
{
"persentage": "6",
"value": "43343"
},
{
"persentage": "4",
"value": "95"
},
];
I need to filter it by 2 conditions if sum of persentage will more 90+, I should skip other objects, or if count of objects is more then 6, then I also should skip rest of objects. I have next solution:
let arr2 = [];
const MAX_PESENTAGE = 90;
const MAX_TOP_VALUES = 6;
let accumulatePersentage = 0;
let countOfValue = 0;
for(const elem of arr) {
accumulatePersentage += Number(elem.persentage);
countOfValue++;
if(accumulatePersentage >= MAX_PESENTAGE || countOfValue > MAX_TOP_VALUES) {
break;
}
arr2.push(elem);
}
console.log(arr2)
But I am not sure is it best solution?