Sridhar Raj Sampath Kumar Archive

Cleaner array manipulation using ES5/6/lodash

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

  1. Iterating over a list - Array.forEach()
  2. Transform a list into another by property - Array.map()
  3. Find an element - Array.find
  4. To get a subset of item matching a specific condition - Array.filter()
  5. To compute an aggregate value for the each item of an array - Array.reduce()
  6. To test if some elements from the array implements the function - Array.some()

Let see each of them with their native and lodash counterparts with examples.

1. Iterating over a list

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.

2. Transform a list into another by property -- map

Array.map returns a new array with results by calling the provided function.

3. Find an element -- find

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.

4. To get a subset of item matching a specific condition -- filter

Array.filter makes it easy to get list of items based on specific property.

5. To compute an aggregate value for the each item of an array - reduce

Array.reduce is used to apply the given function to each item of the collection and reduce them to a single value.

6.To test if some elements from the array implements the function -- some

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.

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