Post/Code

HomeAboutUsesNow

Arrays in JavaScript.

The past few years, working with JavaScript, the for loop was the go-to tool I used for iterating and working on collections. Over the last few months, as I have adopted more modern JavaScript and TypeScript, the functions below have started to become a daily part of my development habits:

Array.map

Array.map lets you iterate over an array and it will return a new array, as follows:

const result = array.map(item => { ... do something making use of each item...});

What's great about this is that it does not mutate the original array. Additionally, you can added second parameter to get the index of the item, like so:

const result = array.map((item, index) => {
    ... do something making use of item and index
});

Array.filter

Array.filter, similarly, lets you iterate over an array, using a conditional to filter the array according to some criteria:

const filteredResult = array.filter(item => ... check against some condition... );

Again, you can get a hold of the index by passing a second parameter like:

const filteredResult = array.filter((item, index) => ... check against some condition... );

Array.slice

While this is not so new, Array.slice is useful since it returns a copy and does not mutate the original:

const slicedResults = array.slice(startIndex, endIndex); // end index is *not* included

You could also achieve a similar result as above by using lodash like so:

import _ from 'lodash'

const result = _(array).slice(startIndex).take(numOfItems).value();

Array.reduce

Another very useful function is Array.reduce. What this does is that it reduces the array to a single value by performing some computation on the items. It take two parameters, an accumulator and the value. Note, if you need to check against some condition, you will first need to filter your array on the condition and then chain the reduce onto that.

const result = array.filter(item => ... do some check against a condition ...).reduce((accumulator, value)) => {... do some calculation...});

The above are so much simpler to work with than for loops once you get a hold of them!