Reputation: 566
I'm trying to check whether o_
against each object exists or not. I'm doing this with .every()
.Can we do this with .reduce()
? What is the performance comparison between these two ?
const obj = level1.level2[level1.ID][P1];
checker = ['o_1', 'o_2', 'o_3', 'o_4'].every(key => obj[key] === undefined);
Upvotes: 2
Views: 1208
Reputation: 50684
Most (if not all) of JavaScript's higher-order array methods can be implemented using .reduce()
, however, there can be differences. In this case, the .every()
method will immediately return false
as soon as it finds that the predicate (ie the callback) returns false. This allows .every()
to terminate its iteration early. However, .reduce()
doesn't have such early-termination functionality, and so, once the callback returns false
, it will keep checking all other remaining values in the array.
For example, the following stops comparing elements once n < 3
is false
:
const arr = [1, 2, 3, 4, 5];
const smaller_than_three = arr.every(n => {
console.log("executing for " + n); // doesn't execute for 4 or 5 as we already know the result is false when `n` is 3
return n < 3
});
console.log(smaller_than_three);
However, implementing the same logic using .reduce()
doesn't terminate the "loop" early:
const arr = [1, 2, 3, 4, 5];
const smaller_than_three = arr.reduce((acc, n) => {
console.log("executing for " +n +", when result is: " +acc); // keeps executing, even after acc is `false`
return acc && n < 3;
}, true);
console.log(smaller_than_three);
In terms of performance, this means that .every()
can have O(1) best case and O(n) worst case. But .reduce()
will have a best and worst case of O(n) (assuming you do constant work within the callbacks for both every and reduce).
Upvotes: 4
Reputation: 2061
.every()
returns a boolean - true if every element in this array satisfies the provided testing function. An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.
.reduce()
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Upvotes: 3