Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
How to make array of object with limmited values

Sorry, in advance if the title is unclear, but it's hard to describe it in a words.

What I have:

const obj = {
 a: 5,
 b: 3,
 c: 0,
 d: 9
}

What I want to have:

const arr = [[a, 5] ,[b, 3]]

Basically, I try to write a function that return me array of entries, but it has too meet requirements:

  • don't want objects when values is equal to 0
  • sum of values must be less than 10

First point is easy for me and I can do it by

Object.entries(obj).filter(([k, v])=> v !== 0)

but I can't handle with the second one.

May I use reduce here?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use a closure and an IIFE to store the sum

Object.entries(obj).filter((() => {
  let sum = 0;
  return ([k, v]) => { sum += v; return v !== 0 && sum < 10; }; 
})());

Examples:

function convert(obj) {
  return Object.entries(obj).filter((() => {
    let sum = 0;
    return ([k, v]) => { sum += v; return v !== 0 && sum < 10; }; 
  })());
}

const obj = { a: 5, b: 3, c: 0, d: 9 };
const arr = convert(obj);
console.log(arr);

const obj2 = { a: 0, b: 0, c: 8, d: 0, e: 1, f: 5 };
const arr2 = convert(obj2);
console.log(arr2);

const obj3 = { a: 12 };
const arr3 = convert(obj3);
console.log(arr3);

about 4 years ago · Juan Pablo Isaza Report

0

@jabaa's answer is great and you should accept it.

Just to confirm your intuition, you could have used reduce, but it would get rather complicated:

const obj = {
 a: 5,
 b: 3,
 c: 0,
 d: 9
}

const result = Object.entries(obj).reduce(
  (o, newPair) => {
     o.sum += newPair[1];
     newPair[1] !== 0 && o.sum < 10 && o.pairs.push(newPair);
     return o;
  },
  {
     sum: 0,
     pairs: []
  }
).pairs;

console.log(result)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!