Ted
Ted

Reputation: 1760

Filter object values in array

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?

Upvotes: 0

Views: 68

Answers (1)

Đinh Carabus
Đinh Carabus

Reputation: 3496

You could use reduce like this:

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" }
];

const filtered = arr.reduce((acc, item, i) => {
  acc.percentage += Number(item.persentage);
  if (acc.percentage <= 90 && i < 6) {
    acc.items.push(item);
  }
  return acc;
}, {percentage: 0, items: []}).items;

console.log(filtered);

Upvotes: 1

Related Questions