Array is the integral part of any modern programming language. In Java script, you have different inbuilt methods for array operations. This article will describe how you can write clean, readable program for variety of array manipulation requirements using inbuilt ES5/6 and lodash functions.
Following are the few common array manipulation functions we use
Array.forEach()
Array.map()
Array.find
Array.filter()
Array.reduce()
Array.some()
Let see each of them with their native and lodash
counterparts with examples.
Array.forEach
is the ES5 standard for iterating over a list of items. It is better than conventional for
loop,
without needing a separate variable for keeping track of index.
Array.map returns a new array with results by calling the provided function.
Array.find
is an ES6 standard. It returns the first matching element, If it is not present, it returns an
undefined
. _.findLast
is identical to this, except it runs the search from right to left
returning the last matching element.
Array.filter makes it easy to get list of items based on specific property.
Array.reduce is used to apply the given function to each item of the collection and reduce them to a single value.
This function will be handy to test, if at least one element in the array implements the function.
Using lodash over the native functions has few advantages.
Array.find
are supported by the modern browsers starting from IE9. Legacy browsers could require
polyfills to work.
undefined
are handled better by lodash than native ES5/6 functions. When the input turns
undefined
they don't error out.
This post uses few ES6 features like fat arrows function, string template, let. For the complete list of ES6 features, head over to babel docs
For my new posts, Subscribe via weekly RSS, common RSS or Subscribe via Email