An Array of JavaScript Array Methods

Follow us on LinkedIn for our latest data and tips!

It is no real surprise that one of the primary purposes of computer languages is processing lists (indeed, one of the oldest programming languages – Lisp – is a contraction of the term “list processing”). In Javascript, lists are managed with the Array object. The last few years has seen a significant beefing up of what JavaScript arrays can do as part of the EcmaScript 6 development, to the extent that even many programmers aren’t aware of the full capabilities that arrays offer.

Explore JavaScript Courses

The following is a mixed bag of tricks and methods, focusing both on some of the cooler ES6 code, some on the more esoteric functional programming tricks of ES5. One thing that both of these improvements do is to establish a unifying principle for iterating through lists of items, a problem that’s emerged from twenty years of different people implementing what was familiar to them in JavaScript. That’s admittedly a testimony to how flexible Javascript is.

Avoiding the Index

The traditional way of iterating over an array has been to use indexes, such as the following (Method 1).

var colors = [“red”,”orange”,”yellow”,”green”,”blue”,”violet”];
for (var index=0; index<colors.length; index++){
    var color = colors[index];
    // do something with color

Method 1. Using index to iterate over an array

The problem with this is that it first requires the declaration and creation of an index variable, and you still have to resolve the value that the array has at that index. It’s also just aesthetically unpleasing – the emphasis is on the index, not the value.

ES6 introduces the of keyword, which lets you iterate to retrieve an object directly (Method 2)

var colors = [“red”,”orange”,”yellow”,”green”,”blue”,”violet”];
for (const color of colors){
     // do something with color

Method 2. Using the of keyword to iterate over a JavaScript array.

The use of this construction is both shorter and with a much clearer intent, retrieving each color from the list without having to resolve an array position. The use of the const keyword also provides a bit of optimization – by declaring the variable color as constant, JavaScript can reduce the number of pointer resolutions because a new variable isn’t declared each time.

If you’ve ever had to process web pages to retrieve specific elements, you likely also know that the result of functions such as document.getElementsByClassName() is array-like, but not strictly an array. (You have to use the item() keyword on the resulting object instead). The ES6 from () function is a static function of the Array object that lets you convert such objects into JavaScript arrays (Method 3).

var colorNodes = Array.from(document.getElementsByClassName(“color”));
for (const colorNode of colorNodes){
     // do something with colorNode

Method 3. Converting an array-like object into a JavaScript array.

By the way, how do you know that colorNodes is an array? You use the static Array.isArray() function (Method 4):

if (Array.isArray(colorNodes)) {
    console.log(“I’m an Array!”)

Method 4. Testing for an array.

Array-like objects, on the other hand, will self- identify (using the typeof keyword) as objects, or will return false to the .isArray() function. In most cases, so long as an interface exposes the length property, it should be possible to convert it into an array. This can be used to turn a string into an array of characters with a single call (Method 5). Note that Array.from(str) is functionally equivalent to str.split(“”), though possibly not as fast.

function strReverse(str){
   return Array.from(str).reverse().join("");

> "tpircSavaJ"

Method 5. Inverting a string

In this example, the strReverse() function using from() to convert a string into an array of characters, then uses the Array reverse() function to reverse the order, followed by the join(“”) function to convert the array back into a string.

Prepositional Soup: From In to Of

The of keyword is easy to confuse with the in keyword, though they do different things. The of statement, when applied to an array, returns the items of that array in the order of that array (Method 6).

var colors = ["red","orange","yellow","green","blue","violet"];
for (const color of colors){
> "red" 
> "orange" 
> "yellow" 
> "green"
> "blue" 
> "violet"

Method 6. The on keyword returns the values of a JavaScript array.

The in keyword, on the other hand, returns the index keys of the array.

var colors = ["red","orange","yellow","green","blue","violet"];
for (const colorIndex in colors){console.log(colorIndex)}
> 0
> 1
> 2
> 3
> 4
> 5

Method 7. The in keyword returns the keys or indices of a JavaScript array.

Note that Javascript arrays, unlike Java arrays, can be sparse. This means that you can have an element a[0] and a[5] without having an a[1] through a[4]. Iterating over the length of an array in this case can cause problems as the length of the Array does not necessarily correspond to the last item in that array (listing 8).

var a= [];
a[0] = 10;
a[5] = 20;
for(var index=0; index!=a.length; index++){
// Returns null values for a[1} to a[4} and a[6], because these have not been defined.
// Note that a.length here is equal to 7.
for(var index in a){console.log(index+": "+a[index])};
// Here, only two values are returned, because, for a[0] and a[5] respectively, because
// the "in" keyword is iterating only on declared keys.
> 0: 10
> 5: 20

Method 8. Sparse arrays can give problems for iterated indexes, while in provides better support.

The Joy of Higher Order Functions with JavaScript Arrays

Callbacks have become an indispensable part of Javascript, especially with the popularity of jQuery and related browser frameworks and the node.js server. In a callback, a function is passed as an object to another function. Sometimes these callbacks are invoked by asynchronous operations (such as those used to make asynchronous calls to databases or web services), but they can also be passed to a plethora of Array related iteration functions.

Perhaps the simplest of such callbacks is that used by forEach(). The principle argument is the function to be invoked, passing as parameters both an object and its associated key or index:

        console.log(key+": "+obj)

> 0: red
> 1: orange
> 2: yellow
> 3: green
> 4: blue
> 5: violet

Method 9. Invoking a function using the forEach() function.

The forEach() function, while perhaps the most commonly known of the “functional” Array functions, is intended primarily to execute an expression without providing a resulting output. If, on the other hand, you want to chain functions together, a more useful Array function is the map() function, which takes the output of each function and adds it to a new array. For instance, the following function (Method 10), takes an array of lower case characters and returns an array where the first letter of each word has been capitalized.
        return obj[0].toUpperCase() + obj.substr(1);

> ["Red", "Orange", "Yellow", "Green", "Blue", "Violet"]

Method 10. Using the map() function.

Note that this function can be extended to turn a sentence into “title case” where every word is capitalized (listing 11).

function titleCase(str){
return str.split(" ")
        return obj[0].toUpperCase() + obj.substr(1);
.join(" ")

var  expr = "This is a test of capitalization.";
> "This Is A Test Of Capitalization."

Method 11. Using array functions to capitalize expressions.

As should be obvious, the split() and join() functions bridge the gap between strings and arrays, where split converts a string into an array using a separator expression, and join() takes an array and joins the strings within the array back together, with a given separator.

What’s even cooler about split() is that it can also be used with regular expressions. A common situation that arises with input data is that you may have multiple spaces between words, and you want to remove all but a single space. You can use split and join (listing 12), to do precisely that.

var expr = "This is  an    example    of   how you   clean up text with embeddedt 
tabs,  white spacesn and even carriage returns."
> "This is &nbsp;an &nbsp;&nbsp;&nbsp;example &nbsp;&nbsp;&nbsp;of &nbsp;&nbsp;how you
&nbsp;&nbsp;clean up text with embedded &nbsp;tabs, &nbsp;white spaces
and even carriage returns."
expr.split(/s+/).join(" ")
> "This is an example of how you clean up text with embedded tabs, white spaces and even carriage returns."

Explore JavaScript Courses

Method 12. Using arrays to clean up “dirty” text.

While touching on dirty data, another useful “functional” Array function is the filter() function, which will iterate over an array and compare the item against a particular expression. If the expression is true, then the filter() function will pass this along, while if it’s false, nothing gets past. If you have data coming from a database, certain field values may have the value null. Getting rid of these (or some similar “marker” value) can go a long way towards making that data more usable without hiccups (Method 13).

var data = [10,12,5,9,22,18,null,21,17,null,3,12];
        return obj != null
> [10, 12, 5, 9, 22, 18, 21, 17, 3, 12]

Method 13. Filter cleans up dirty data.

This notation is pretty typical of Javascript – powerful but confusingly opaque with all of these callback functions. However, it turns out that there are some new notational forms in ES6 that can make these kinds of functions easier to read. The predicate construct

(arg1,arg2,…) => expr involving arg1,arg2,…

can be used to make small anonymous functions. Thus,

(obj, index) => (obj != null)

Is the same as

function(obj, index){return (obj != null)};

With this capability, you can write Method 13 as:

data.filter((obj)=> obj != null);

You can even use this notation to create named functions (Method 14).

dropNulls = (obj) => (obj != null)

Method 14. Using predicate notation to define named functions for filters.

You can also go one step further and just say:

dropNulls = (arr) => arr.filter((obj) => obj != null)

Counter tof filter() is find() , which returns the first item (not all items) where the predicate is true. For instance, suppose that you wanted to find from an array the first value that is greater a given threshold. The find() function can do exactly that (Method 15).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
data.find((item) => item>10)
> 12

Method 15. Use find to get the first item that satisfies a predicate.

Note that if you wanted to get all items where this condition is true then simply use a filter (Method 16).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
data.filter((item) => (item>10))
> [12, 22, 18, 21, 18, 12]

Method 16. Find retrieves the first value satisfying a predicte, filter, retrieves all of them.

The findIndex() function is related, except that it returns the location of the first match, or -1 if nothing satisfies the predicate.

Did you know that JavaScript Arrays can do map/reduce? This particular process, made famous by Hadoop, involves a two-step process where a dataset (an array) is initially mapped to another “processed” array. This array is then passed to a reducer function, which takes the array and converts it into a single processed entity. You can see this in action in Method 17, which simply sums up the array values, but shows each of the arguments in the process:

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
    console.log(prev+", "+current+", "+index+", "+arr);
    return prev+current},
> 0, 10, 0, 10,12,5,9,22,18,21,17,3,12
> 10, 12, 1, 10,12,5,9,22,18,21,17,3,12
> 22, 5, 2, 10,12,5,9,22,18,21,17,3,12
> 27, 9, 3, 10,12,5,9,22,18,21,17,3,12
> 36, 22, 4, 10,12,5,9,22,18,21,17,3,12
> 58, 18, 5, 10,12,5,9,22,18,21,17,3,12
> 76, 21, 6, 10,12,5,9,22,18,21,17,3,12
> 97, 17, 7, 10,12,5,9,22,18,21,17,3,12
> 114, 3, 8, 10,12,5,9,22,18,21,17,3,12
> 117, 12, 9, 10,12,5,9,22,18,21,17,3,12
> 129

Method 17. The reduce() function takes an array and processes content into an accumulator.

The first column shows that result of adding the current value to the accumulator (initially set to initializer, the 0 value given as the second argument of the reduce() function), the second column gives the current value itself, the third item is the index, and the final item is the array.  

A perhaps more realistic example would be a situation where a tax of 6% is added to each cost, but only for values above $10. Again, you can use predicate maps to simplify things (Method 18).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
total = data.reduce((prev,current) => (prev + current + ((current>10)?(current-10)*.05:0)),0);
console.log("$" + total.toLocaleString("en"))

> "$131.52"

Method 18. Using the reduce() function to calculate a total with a complex tax.

The .toLocaleString() function is very useful for formatting output to a given linguistic locale, especially for currency. If the argument value “de” is passed to the function, the output would be given as “131,52”, where the comma is used as the decimal delimiter and the period is used for the thousands delimiter.

How Do Your Arrays Stack Up?

When I was in college, cafeterias made use of special boxes that had springs mounted in the bottom and a flat plate on which you could put quite a number of trays. The weight of each tray pushed the spring down just enough to keep the stack of trays level, and when you took a tray off, it rose so that the last tray placed on the stack was always the first tray off. This structure inspired programmer who discovered that there were any number of situations where you might want to save the partial state of something by pushing it down on an array, then when you were done processing, popping the previous item back off. Not surprisingly, such arrays became known as, well, stacks.

JavaScript defines four functions – push(), pop(), shift(), and unshift() respectively. Push() places an item on the end of an array, pop() removes and returns it. You can see this in Method 19.

var stack = ["a","b","c"];
> ["a", "b", "c"]
> 4
> ["a", "b", "c", "d"]
> ["a", "b", "c"]
> ["d", "a", "b", "c"]
> ["a", "b", "c"]

Method 19. Pushing and popping the stack.

Stack based arrays have a number of uses, but before digging into them, you can extend the Array() functionality with a new function called peek() that will let you retrieve the last item in the array (which is the top of the stack), as shown in Method 20.

Array.prototype.peek=function(){return this[this.length-1]};
arr = ["a","b","c","d","e"]

Method 20. Peeking at the stack.

(Note that you can always get the first items in an array with arr[0]).

One of the more common use for stacks is to maintain a “browse” history in a Javascript application. For instance, suppose that you have a data application where render(id) will draw a “page” of content without doing a server-side reload. Method 21 shows a simple application that keeps a stack which will let you add new items as you continue browsing the stack, but also lets you back up to previously visited “pages”.

<!DOCTYPE html>
<html xmlns="">
#container,#list {color:white;}            
Array.prototype.peek=function(){return this[this.length-1]};

App = {
       App.container = document.getElementById("container");
       App.colorSelect = document.getElementById("colorSelect");
       App.popButton = document.getElementById("popButton");
       App.list = document.getElementById("list");
       return false;
       color = App.colorSelect.value;
       oldColor = App.color;
       App.color = color;
       App.list.innerHTML = App.stack;        
       var oldColor = App.stack.pop();
       if (oldColor != null){
           App.list.innerHTML = App.stack;
       return false;

       <div id="container"></div>
       <select value="white" id="colorSelect">
           <option value="white">White</option>
           <option value="red">Red</option>
           <option value="green">Green</option>
           <option value="blue">Blue</option>
           <option value="orange">Orange</option>
           <option value="purple">Purple</option>
       <button id="popButton">Pop</button>
       <div id="list"></div>

Method 21. Creating a stack that remembers color states.

When you select an item from the <select> box, it changes the background to the new color, but then pushes the old color onto the stack (shown as the comma separated list). When you pop the item, the stack removes the last item and makes that the active color.  This is very similar to the way that a web browser retains its internal history.



Contemporary Javascript arrays are far more powerful than they have been in the past.  They provide a foundation for higher order manipulation of functions, let you do filtering and searching, and can even turn complex functions (often ones that relied heavily upon recursion) into chained map/reduce operations. This should make arrays and array functions a staple for both text processing and data analysis. Learning how to work with arrays properly can give you a distinct advantage as a Javascript programmer.

Explore JavaScript Courses

One final note: While ES6 is rapidly making its way into most contemporary browsers and environments such as node.js, they may not necessarily be available in older browsers (especially constructs like of and predicates). There are a number of polyfill libraries that will let you get close, most notably the Babel polfill (

Kurt Cagle is the founder and chief ontologist for Semantical, LLC, a smart data company. He has been working with Javascript since 1996.