Below, you’ll find a few code samples of JavaScript that I often use and would like to save a quick reference.
Does an array contains a value
Use includes if the value to find matches the type of each value in the array.
|
|
Does an array contains only truthy values
Use reduce with the initial value to true and if all value are true then the result is true too.
|
|
Sum up values
Again, use reduce for this scenario:
|
|
Of course, make sure all values are numbers or floats to avoid issues. For that:
- use the hard way by checking the
nextvariable type and exclude it if not a number (NaN is a number…). - use the future-proof way with TypeScript to make sure nothing else than a number to be pushed into the array.
Remove an item from an array
Use splice: it is quick and simple to understand.
|
|
Extract one property from a list of objects
Use flatMap:
|
|
If prop, the value is undefined.
Shuffle values of an array
|
|
More to come…
Save this page as I’ll add more as I practice and work on projects.
Thanks for reading.
Credit: Photo by Sudharshan TK on Unsplash.