Hello I am back after programming after a few months doing very little and I think I have lost my brain.
just for the sake of it (and for learning reduce) i want a function that returns true if for example 3 the value “3” is in the array [1,2,3,4,5]
can I do that? I guess the idea of accumulator and current value, but I am not sure how to implement it with booleans.
snigo
December 17, 2019, 1:27pm
#2
Nice idea, or you can just:
One quick solution using reduce:
[1,2,3,4,5].reduce((acc, next) => {
if (acc === true) return acc;
if (acc === 3 || next === 3) return true;
return false;
});
Of course there’s no particular reason you should need a reducer here.
You could use filter
// !! is used to get a boolean value. Length will already be truthy or falsey
!!([1,2,3,4,5].filter(x => x === 3).length)
You can use includes
[1,2,3,4,5].includes(3)
You can use indexOf
[1,2,3,4,5].indexOf(3) >= 0
And possibly other methods that arent on my mind at the moment!
EDIT: @ilenia ’s version below, with an initial value supplied, is much much cleaner and a preferable refactor imo.
3 Likes
ilenia
December 17, 2019, 1:29pm
#4
with reduce you can do a lot of things.
I can think of something like this:
arr.reduce((boolean, number) => number === 3 || boolean, false);
(you can easily change it from an implementation of includes
to an implementation of every
by using &&
instead of ||
3 Likes
Thanks a lot.
I was not keeping track of the accumulator, i did not…
if (accumulator === true) return true
so my “true” was drowning in the sea of undefined
In case you are curious. The idea of using reduce is to create a object validator, a simplified schema testing function, but i guess that the method “every()” does that better
But the main point was to help me remember how reduce works
If you find yourself in need of robust object validation, you might take a look at open source modules like joi (docs , github ).
Even if you don’t need it or use it, reading the source might produce some useful insights that you can incorporate in your own toolkit.
1 Like