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?
CodePudding user response:
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:
const obj = {
a: 5,
b: 3,
c: 0,
d: 9
}
const arr = Object.entries(obj).filter((() => {
let sum = 0;
return ([k, v]) => { sum = v; return v !== 0 && sum < 10; };
})());
console.log(arr);
const obj2 = {a: 0, b: 0, c: 8, d: 0, e: 1, f: 5};
const arr2 = Object.entries(obj2).filter((() => {
let sum = 0;
return ([k, v]) => { sum = v; return v !== 0 && sum < 10; };
})());
console.log(arr2);
const obj3 = {a: 12};
const arr3 = Object.entries(obj3).filter((() => {
let sum = 0;
return ([k, v]) => { sum = v; return v !== 0 && sum < 10; };
})());
console.log(arr3);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
@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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>