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
Let see each of them with their native and
lodash counterparts with examples.
is the ES5 standard for iterating over a list of items. It is better than conventional
without needing a separate variable for keeping track of index.
Array.map returns a new array with results by calling the provided function.
is an ES6 standard. It returns the first matching element, If it is not present, it returns an
_.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.findare supported by the modern browsers starting from IE9. Legacy browsers could require polyfills to work.
undefinedare handled better by lodash than native ES5/6 functions. When the input turns
undefinedthey don't error out.