Knowledge Seeker
Knowledge Seeker

Reputation: 566

.reduce in lodash fucntionality

I'm trying to figure out whether all three objects are defined or not in a optimized and less code. For that purpose, I'm using lodash with reduce. But It is not giving me the correct value. Am I using reduce in a wrong way ?

checker1 = ((level1.test[testState.Id]['p1']['o1'] == undefined) && 
(level1.test[testState.Id]['p1']['o2'] == undefined) && 
(level1.test[testState.Id]['p1']['o3'] == undefined))
console.log('checker',checker1) //true


checker2 = _.reduce(level1.test[testState.Id] ,
                            (checker, val) => {return checker || (val == undefined)}, false)                  
console.log('checker',checker2) //false! It should be true!

Upvotes: 1

Views: 133

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074208

Your input to _.reduce is just level1.test[testState.Id], which seems to be a non-array object. Nothing in that code tells _.reduce it would work on the .p1.o1, .p1.o2, and .p1.o3 properties on the object.

If you want to use reduce for this, I'd use the native one and start with an array of property names:

checker2 = ['o1', 'o2', 'o3'].reduce(
    (checker, prop) => checker && level1.test[testState.Id].p1 === undefined,
    false
);

... in a optimized and less code

reduce doesn't do either of those things. It requires creating an array and multiple function calls. Instead:

const obj = level1.test[testState.id].p1;
checker = obj.o1 === undefined && obj.o2 === undefined && obj.o3 === undefined;

(If you are going to use an array and callbacks, use every as AKX points out.)

Upvotes: 1

AKX
AKX

Reputation: 168913

It'd be easier (and more performant, as it has early-exit properties) to use Array.every:

const obj = level1.test[testState.Id].p1;
const checker1 = ['o1', 'o2', 'o3'].every(key => obj[key] === undefined);

Upvotes: 4

Related Questions