Most Useful JavaScript Array Functions

Most Useful JavaScript Array Functions

In this JavaScript Tutorial, we’ll take a look at the Most Useful JavaScript Array Functions. For this tutorial, we took the source code from the pros and put it all in one bucket. The source code from the pros would be the JavaScript that powers the most popular JavaScript frameworks today, such as Angular, React, Vue, Mithril, and countless more. Once we have all of this source code in the same file, we check for the number of times each array function was made use of in the code. Of course JavaScript array functions that had a very high number of calls to them are featured first, as this would suggest that those particular functions are very useful to the pros. Array functions that were not used all that often are placed lower on the list. Let’s see which ones made it to the top of our most useful JavaScript array functions list.

  • 1What are JavaScript Arrays?
  • 2Array.prototype.push()
  • 3Array.prototype.indexOf()
  • 4Array.prototype.slice()
  • 5Array.prototype.toString()
  • 6Array.prototype.filter()
  • 7Array.prototype.join()
  • 8Array.prototype.splice()
  • 9Array.prototype.forEach()
  • 10Array.prototype.concat()
  • 11Array.prototype.shift()
  • 12Array.prototype.unshift()
  • 13Array.prototype.map()
  • 14Array.prototype.sort()
  • 15Array.prototype.pop()
  • 16Array.prototype.reduce()
  • 17Array.prototype.some()
  • 18Array.prototype.lastIndexOf()
  • 19Array.prototype.reduceRight()
  • 20Array.prototype.every()
  • 21Array.prototype.reverse()

  • 1. What Are JavaScript Arrays?

    In JavaScript, an Array represents an ordered collection of values. The array consists of one or more elements, each having a numbered position inside of the array. This is also called the index. Any given array element can hold any type offered by the JavaScript language. In other words, you can mix and match the various types inside of the same array. Just like most programming languages, arrays in JavaScript are zero based. This means they start at 0 and move up from there. Arrays in JavaScript grow and shrink like magic. That is to say, you do not have to specify the array size ahead of time before placing values in the array. As you add elements, the array dynamically grows for you. The same happens when you remove elements. All JavaScript arrays have a link to Array.prototype which is how we get access to all of the very useful functions we’ll cover here in this tutorial. In true JavaScript style, these functions work not only on any array, but also any “array-like” object.


    2. Array.prototype.push()

    array.push(element1, …, elementN)

    Overview

    The push() function appends the arguments given to it, in order, to the end of the array. It modifies the array directly, rather than creating a new array.

    What push() returns

    When you make a call to push(), it returns the total number of items in the array, after any provided arguments have been added to the end of the array.

    array.push() function examples


    3. Array.prototype.indexOf()

    array.indexOf(searchElement[, fromIndex = 0])

    Overview

    The JavaScript indexOf() function searches an array for an element that contains a specific value, then returns the very first index that contains that value. You can provide a starting index to the function if you like, otherwise searching will begin from index 0.

    What indexOf() returns

    The lowest index that is greater than or equal to the start of the array at which the element is equal to the given value. If no match is found, the indexOf() function returns -1.

    array.indexOf() function examples

    The example above is a little more tricky. We have an array of enemies, and there might be multiple of a given enemy. By making use of indexOf(), we can find all instances of ‘Storm Trooper’ in our array of enemies. Running the code shows us that we have found a Storm Trooper at index 2 and index 5 of our array.

    This example makes use of a custom function that we can use to make sure our good guys are all accounted for. We check to see if the character exists in our collection, and if not, we add them to our good side.


    4. Array.prototype.slice()

    array.slice([begin[, end]])

    Overview

    The JavaScript slice() function takes a start and end argument. It uses these start and end points to reach into the array, and remove a specific number of elements. The position you reference by start is included in the results, but the end is not included. In other words all elements are returned from the start right up to, but not including the end element. If you do not provide an end value, slice() will return the rest of the array starting from the given starting point. The original array is left in tact.

    What slice() returns

    The slice() function returns a new array that contains all of the elements of the original array from the element specified by the starting point provided, and up to but not including, the element specified by the ending point provided.

    array.slice() function examples


    5. Array.prototype.toString()

    array.toString()

    The toString() function converts all elements in an array to strings and outputs one big string as a comma separated list of items.

    array.toString() function examples


    6. Array.prototype.filter()

    array.filter(callback[, thisArg])

    Overview

    The JavaScript filter() function is very useful for doing exactly what it says, filtering down a collection of elements based on a given test. When you call the filter() function, you need to pass it a callback. This callback is executed against every element in the array. If that callback results in a true value, that particular element is added to a new array. The original array is left unchanged.

    What filter() returns

    filter() returns a new array that contains only the elements of the original array that returned true when the provided callback ran.

    array.filter() function examples


    7. Array.prototype.join()

    string = array.join([separator = ‘,’])

    Overview

    The join() function converts each element of an array to a string and then concatenates those strings together. If the separator string was provided, it gets inserted between all elements in the final string.

    What join() returns

    The string that results from converting each element of the original array to a string and then joining them together, with the separator string between elements.

    array.join() function examples


    8. Array.prototype.splice()

    array.splice(start, deleteCount[, item1[, item2[, …]]])

    Overview

    The splice() function deletes zero or more elements beginning from the provided start location, and replaces those elements with zero or more new values that were provided. Existing items in the array are shifted as needed to make room for any added or deleted elements. The thing to remember about the splice() function, is that it does modify the original array directly.

    Returns

    An array which contains any elements that may have been deleted from the array.

    array.splice() function examples


    9. Array.prototype.forEach()

    array.forEach(callback[, thisArg])

    Overview

    The forEach() function executes a provided function on each element of the array. forEach() has no return value and does not return the original array. forEach() is related to the map(), filter(), every(), and some() functions and as such they share some related details. They all expect a callback function as the first argument. The optional second argument is a way to specify the this value for the callback function. All of these functions check the length of the array before looping. If the provided callback adds elements to the array during it’s execution, those elements are not included for looping by the forEach(). Also of interesting note is that if the callback changes values in the original array before they are looped over, those changed values will be passed during their callback execution.

    array.forEach() function examples


    10. Array.prototype.concat()

    var new_array = old_array.concat(value1[, value2[, …[, valueN]]])

    Overview

    concat() is a function that creates a new array which is the result of adding the supplied arguments to the original array. The original array is left intact, and the new array is the original plus any added elements. If any of the arguments to the concat() function are themselves an array, then the elements of that supplied array are added, rather than the entire array itself.

    Returns

    A new array, which is created by adding each of the supplied arguments to the original array.

    array.concat() function examples


    11. Array.prototype.shift()

    array.shift()

    Overview

    The shift() function removes and returns the first element of the original array. All remaining elements in the array get shifted one slot to the left in order to fill the hole created by removing the first element. If you try to apply this function to an empty array, it will do nothing and simply return undefined. The shift() function does not create a new array, it modifies the original array directly.

    Returns

    shift() returns the first element from the original array.

    array.shift() function examples


    12. Array.prototype.unshift()

    array.unshift([element1[, …[, elementN]]])

    Overview

    A direct opposite to the shift() function which we just discussed, is the unshift() function. unshift() inserts any arguments you pass to it into the beginning of the array. All of the existing elements need to shift to the right in order to make room for the new elements. Each argument passed to unshift() gets added in order starting from index 0. In addition, unshift() is modifying the original array directly.

    Returns

    The new length of the array.

    array.unshift() function examples


    13. Array.prototype.map()

    array.map(callback[, thisArg])

    Overview

    This is a very useful JavaScript function, and made use of all the time in professional software. The map() function loops over every element in the array, executing a callback function on each item. Once map() has completed looping through the array, it takes the results from each callback applied to each element, and returns those results in their entirety as an array. You are left with a new array with updated values, and an old array which has the original values. These two arrays are equal in length. When the callback is invoked, it is done so with three arguments. Those are the value of the element, the index of the element, and the Array object being traversed. If the optional second parameter is provided to map(), it will be used as the this value for each execution of the callback.

    note: The map() and forEach() functions seem like they are the same, but they are in fact different. The difference is that forEach() iterates over an array and applies some operation with side effects to each array member such as saving each one to the database, or some other side effect. map() on the other hand iterates over an array, updates each member of that array, and returns another array of the same size with the transformed members (such as converting an array of strings to all lowercase).

    Returns

    map() returns a new array with elements computed by the provided callback function.

    array.map() function examples


    14. Array.prototype.sort()

    array.sort([compareFunction])

    Overview

    If you want to sort an array in JavaScript, then you can do so with the built in sort() function. sort() applies the sort directly to the original array, no copy of the array is made. You can optionally provide a callback function that will determine the behavior of the sort. If you do not provide one, the sort() function will first convert all elements to strings, and then sort based on something called the Unicode code point value. Basically that means alphabetical, but with some special rules such as capital letters coming before lowercase.

    Returns

    sort() returns a reference to the original array.

    array.sort() function examples

    As we can see from the above example, when you do not supply a callback function to the sort method, ordering may not be what you expect. The rules for ordering in Unicode are a bit unique. For example, numbers come before upper case letters and uppercase letters come before lowercase letters. In addition, an array of numbers is converted to strings before sorting, so this is why we see 33 coming before 4 and 9 in the example above. Here is a callback function example to show ordering numbers how you might expect.


    15. Array.prototype.pop()

    array.pop()

    Overview

    The opposite of the push() function would be the pop() function. The pop() function removes the last element from an array, decrements the length of the array, and returns the value which was removed from the array. If you try to apply the pop() to an empty array, you will simply get undefined returned.

    Returns

    pop() returns the last element of the array it is called on.

    array.pop() function examples


    16. Array.prototype.reduce()

    array.reduce(callback[, initialValue])

    Overview

    reduce() accepts a function as the first parameter which acts like a binary operator. This callback function takes two values, operates on them, and returns a result. The number of times the callback function runs is always one less than the total length of the original array. For example if the original array has a length of 10, the callback will run 9 times. The final result is one combined value.

    Returns

    The reduced value of the array, which is the return value of the last time the callback function is executed.

    array.reduce() function examples

    In this example, we will use array.reduce() to operate on values contained within a simple array of objects. array.reduce() is a little more challenging than some of the other useful array functions, so spend some extra time on this one if it doesn’t click immediately.


    17. Array.prototype.some()

    array.some(callback[, thisArg])

    Overview

    As we can see from the signature above, the some() function takes a callback as the first argument, and an optional second argument. The second argument, if provided, specifies the this value for invocations of the supplied callback. The some() function runs the provided callback on each element in the array, and if the callback returns true, then the some() function stops right away and returns true. If all callback iterations return false, then some() returns false.

    Returns

    some() either returns true or false. At least one item in the array must return true when the callback is applied in order for some() to return true.

    array.some() function examples


    18. Array.prototype.lastIndexOf()

    array.lastIndexOf(searchElement[, fromIndex = arr.length – 1])

    Overview

    The lastIndexOf() function searches through an array backwards for a supplied value. Once the function finds that value, it returns the index position of where that value exists in the array. If you provide the optional second argument to the lastIndexOf() function, searching will begin from that starting point and go backwards. If you do not supply this second argument, searching starts at the end of the array. If no match is found, -1 is returned.

    Returns

    The highest index position that is less than or equal to the start of the array where the element is === to the value you are looking for, or -1 if there are no matches found.

    array.lastIndexOf() function examples


    19. Array.prototype.reduceRight()

    array.reduceRight(callback[, initialValue])

    Overview

    The reduceRight() function works just like reduce() with one key difference. reduceRight() enumerates array elements from right to left (from highest index to lowest) rather than left to right (lowest to highest).

    array.reduceRight() function example


    20. Array.prototype.every()

    array.every(callback[, thisArg])

    Overview

    You can use the every() function to test whether a condition is true for all elements in an array. As like with most looping functions in JavaScript, you are expected to provide a callback function which will run on each element in the array from lowest to highest index. If all iterations return true when the callback runs, then the every() function itself will return true. If however an interation of the callback returns a false value, then every() stops right away and returns false.

    array.every() function example


    Array.prototype.reverse()

    array.reverse()

    Overview

    The reverse() function does exactly what you think it would do. It reverses the order of the elements of they array it is applied to. The reverse() function does this right on the original array, no new array is created or returned. In addition keep in mind that if there are many references to a particular array in your program, and you reverse that array, all references now also see an array which has been reversed. Perhaps that is why this function appears lower on our most useful JavaScript array functions list. Remember, the lower on the list a function appears, the less times we found it in use in popular open source software.

    array.reverse() function example


    Most Useful JavaScript Array Functions Summary

    In this episode we took a look at all of the many useful JavaScript Array Functions you’re likely to make use of and find helpful during your JavaScript programming. We used a method of analyzing popular JavaScript source code repositories hosted on Github, the well known open source software sharing and collaboration website. We found that the most useful JavaScript functions according to the number of times they were used in popular JavaScript frameworks to be Array.push(), Array.indexOf(), Array.slice(), Array.toString(), Array.filter(), Array.join(), Array.splice(), Array.forEach(), Array.concat(), Array.shift(), Array.unshift(), Array.map(), Array.sort(), Array.pop(), Array.reduce(), Array.some(), Array.lastIndexOf(), Array.reduceRight(), Array.every(), and finally, Array.reverse(). It would make sense to memorize as many of these as you can, or at least be very familiar with the ones that appear at the top of the list.