But before you get into brute forcing that new function, you might want to check out Lodash. Because odds are, it already has you covered.
Lodash is amazing for all kinds of things — iterating over arrays, objects, and strings, manipulating values, you name it.
To get started, all you have to do is run
npm install lodash. Then, in the file where you want to use Lodash methods, you can load the full build using
const _ = require('lodash');. You can also just load whichever parts of the build you want to use; check out the docs for more detail on how to do that.
Just to give you an idea of how useful Lodash can be, let’s go through a few of the built-in methods for arrays. Remember, this is just a tiny sample of what Lodash is capable of.
- Compact an array.
Say you have an array with hundreds of elements. You’re trying to downsize this thing, so you want to remove any falsey values — that is, elements equal to
With Lodash, all you need is
_.compact(array);. That’s it.
- Check if something is an array-like value.
.isArray() method. But let’s say you still want the function to return true if the value is array-like — that is, if it has a length and isn’t a function.
For that, you can use Lodash’s
_.isArrayLike(["a", "b", c"]); will return
true, but so will
- Check if two arrays (or objects, or pretty much anything else) are equal.
const a = [1, 2, 3];
const b = [1, 2, 3];
If you try checking
Lodash solves this problem with its enormously powerful
_.isEqual() method. With Lodash, if you check
_.isEqual(a, b);, it will return true.