0

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?

2
  • 1
    "best solution" is of course highly subjective. I'd say your solution does what it's supposed to do, is pretty clean - so don't care too much. Commented Sep 2, 2020 at 18:55
  • it s percentage not persentage that s the only thing you should change Commented Sep 2, 2020 at 18:57

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.