Underscore.js: Working With Array Functions

Many JavaScript frameworks and libraries are currently built to have the developers more productive and to make significant improvement to JavaScript's robustness. JS developers now have several tools that have emerged to work around Functional Programming (FP).

So, this article introduces one such JavaScript utility called Underscore.js that makes the JS developer's work with Functional Programming easier.

Introduction


Underscore.js a JavaScript is a kind of utility library that provides many useful and helpful functions to that makes programming and performs various types of operations with some of the common data structures
used in JavaScript much easier and in Unobtrusive manner. Underscore.js is self-contained; it does not require any other library and any kind of dependency framework and is a very lightweight script to add.
You just simply add a JS file to your HTML page and start exploring it and get the benefits of it's utility methods.

General Purpose

  • It has nothing to do with DOM manipulation (Unlike jQuery).
  • No Functionality specific to web browsers.

The Underscore.js gives us many functions that is around 60 or more that supports common data structures used in JavaScript like anover array (first, last, without and so on), collection (as well as more specialized helper functions for binding, templating and so on).

Underscore creates and exposes all its functionality via a single object, in global scope. This object is the titular underscore character ( _ ) that is similar to the dollar ($) symbol for jQuery. And just like jQuery, you can remap this character in case you run into conflicts.

You can download the library from here.

So, for now we will cover some utility function that works with a very common data structure known as Arrays.

Let's begin using some of the array functions provided by Underscore.js

1. first (head or tail)

   Syntax:

   _.first(array, [n])

   Description:

   As it's name suggests, this method returns the first element of an array. It takes two arguments but the second argument is optional. If we pass the second argument then it will return the first n elements of the array.

   Example:


   With second argument:


2. last

   Syntax:

   _.last(array, [n])

   Description:

   This method is the total reverse of the earlier method. It will return the last element of an array. The second argument is optional; if n is passed then it will return the last n elements of the array.

   Example:


   With second argument:


4. initial

   Syntax

   _.initial(array, [n])

   Description

   Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.

   Example




3. rest (tail, drop )

Syntax

_.rest(array, [index])

Description

This function returns the rest of the elements in an array. The second parameter is an index to return the values of the array from that index onward.

Example

Suppose you want to get all the array values except the 3 values in the beginning.





4. compact

Syntax:

   _.compact(array) 

Description

This is an amazing function of Underscore.js. Every time a developer becomes stuck with JS falsy values such as undefined or null. This function surprisingly removes all the falsy values from the given array and returns a copy of the array with all falsy values removed.

   In JavaScript false, null, 0, "", undefined and NaN are all falsy.

   Example:


5. without

Syntax

   _.without(array, values)

Description

This function is used to remove some of the values that you don't need in array. This function gives you a replica of the array after removing all the instances of the given values from the array.

   Example:



6. uniq (unique)

   Description

Another exceptionally useful method is uniq(). This method accepts a single array as an argument and returns an array containing only the unique items from the source array. This method uses the strict equality test (===) in its comparator function to determine whether or not two items are identical.

Example:



This method can accept a Boolean as the second argument that specifies whether the source array has already been sorted. It has a much faster algorithm to weed out the duplicates. We can pass a transformation function to this method as the third argument. If we were trying to make the method case-insensitive, we could use the following.

Example:



The transformation function receives the "current" item each time it is invoked (it will be invoked for each item in the source array) and should return the transformed item. In this case, we just convert the item to lowercase before returning it. No more casing issues.

7. indexOf


Syntax:

   _.indexOf(array, value, [isSorted])

Description

Returns the index at which the value can be found in the array, or return -1 if the value is not present in the array.

To use indexOf() we supply the array to search as the first argument and the term we are searching for as the second. There is also a third argument that takes a Boolean indicating whether the array is already sorted, that runs a much faster search algorithm like the earlier one uniq().

Example



8. union

Description

You are all very much aware of what a union does. This method takes any number of arrays and returns a single array containing any items that appear in one or more of the original arrays.

Example:





The returned array will contain the items in the order in which the source arrays are passed in.

9. range

Syntax

   _.range([start], stop, [step])

Description

The range() method is used with arrays, but Instead of accept any arrays as arguments, it accepts integers, and uses them to return an array    containing a sequence of numbers.

The argument is uses:

   [start]: The first argument, that is optional and defaults to 0, is the starting number.
   stop: The second argument is the number to stop at.
   [step]: The third argument is the step value.

Example

If a single argument is provided then it is assumed to be the number to stop at and 0 is used as the starting number. 1 is used as the step.

The output of this would be an array containing the values 0, 1 and 9 (remember, array indices are zero-based).

If two arguments are provided then they are assumed to be the starting and stopping number. 2 is used as the step.

This would provide the same result as the first example. To use a step value other than 1 we must provide all three arguments.

This now gives the result 0, 2, 4, 6, 8.

We can provide a lower ending number than the starting number if we wish; in this case, the step value provided should be negative.

In this case, the output is now 10, 8, 6, 4, 2. Although possibly not used as often as the other methods we looked at, range() is nevertheless a useful method when a list of numbers between a specific range is needed.





10. zip

Syntax

   _.zip(*arrays)

Description

The zip() method takes any number of input arrays and returns a number of arrays merged together with the values of each of the arrays with the values at the corresponding position.

Example



When you see the output of this expression, you'll see that the first array returned contains the items “one” and 1, the second array contains the  items “two” and 2, and so on.

Conclusion

Well, that's about it for today. Through this article, we have looked at many methods that are useful for working with array-like structure. There are many other just as useful methods provided by the Underscore library that may help you. You can see the entire cheat sheet of Underscore.js here.

Up Next
    Ebook Download
    View all
    Learn
    View all