Getting To Know JavaScript Built-In Methods — Arrays

Tolani Benson
The Startup
Published in
6 min readMay 23, 2020
Photo by Rich Tervet on Unsplash

This is the third post in my series about JavaScript’s handy built-in methods for different data types (links to the rest of the series are at the bottom of this post). There are a ton of handy ready-made methods which can be used to manipulate data, and I’ll be explaining some of the most useful ones.

This post will be discussing array methods. Arrays are a type of JavaScript object that represents a collection of elements, denoted by square brackets, eg arr = [1,2,3,4]. Every element in an array has an index number, which refers to its position in the array (starting at 0), and allows us to access a specific element using its index — continuing with our previous example, arr[0] would return 1. The elements within the array can be of any data type, including arrays (this would be a nested array), functions and null.

JavaScript Array Methods

arr.length

Returns the number of elements in the array. Empty & null elements are still counted.

Adding, removing & changing elements in arrays:

arr.push(data)

Adds the provided data to the end of the array. Can take multiple comma separated values, which will be added in the same order. Mutates the original array (destructive). The return value is the new array length, not the mutated array itself.

arr.unshift(data)

Adds the provided data to the beginning of the array — can take multiple values. Destructive. The return value is the new array length, not the array.

arr.pop()

Removes the last element from the array. Destructive. The return value is the element that was removed from the array, not the array.

arr.shift()

Removes the first element from the array. Destructive. The return value is the element that was removed, not the array.

arr.slice(startIndex, endIndex)

Returns a slice of the array, starting from the element at the starting index, up to the element before the end index — ie the element at the end index is not included in the selection. Can provide a negative start index, in which case it counts backwards from the final element (eg arr.slice(-2) will return the last 2 elements of the array). End index is optional — if not provided will return all elements from the start index to the end of the array. Non-destructive, returns a copy of the elements selected without mutating the original array.

arr.splice(startIndex, numDelete, dataAdd…)

Not to be confused with slice, splice is destructive and will mutate the original array. It can be used to remove, add, or replace elements at a specific index within an array:

  • The first argument is the index that you want to start from.
  • The second argument is the number of elements you wish to remove — can be set to 0 if you do not want to delete any elements, can be omitted to delete all elements after the start index.
  • The final argument is the data you add into the array — multiple items can be provided to be inserted into the array starting from the start index, or can be omitted if you do not wish to add/replace anything in the array.

The return value is an array of the deleted items, not the mutated array (if none are deleted returns an empty array).

arr.fill(value, startIndex, endIndex)

Replaces items in the array with the provided value. Optional start and end index parameters, if provided will replace from the start index up to the element before (not including) the end index. If no end parameter is provided will replace all elements from the start index, if neither is provided will replace all elements in the array with the value parameter. Destructive. Return value is the mutated array.

Manipulating arrays:

arr.toString()

Returns array converted into a string, with the elements separated by commas, does not add spaces, eg [“the”, “red”, “dog”].toString() returns “the,red,dog”. Not as useful as arr.join() which allows a separator to be specified.

arr.join(separator)

As mentioned above, returns array converted to a string, but with elements separated by provided separator. Eg [“the”, “red”, “dog”].join(“ “) returns “the red dog”. If no separator is provided, behaves the same as toString().

arr1.concat(arr2)

Merges two or more arrays into a new array, without modifying the original arrays. Arguments provided do not have to be arrays, can be of any data type, elements will be added into a new array in the order provided. Returns new merged array.

arr.flat(depth)

Flattens nested arrays by the number of layers provided, and removes any gaps/blank elements in the array— eg [1, ,[3,[4]]].flat(1) returns [1, 3, [4]]. Non-destructive, returns flattened copy of original array.

Finding & testing data within arrays:

arr.find(testFunction)

Returns the first element which satisfies the test function provided.

arr.filter(testFunction)

Returns a new array of all elements which satisfy the test function provided. Non-destructive.

arr.indexOf(value, startIndex)

Returns the index of the first instance of the provided value in the array. Optional second parameter sets a starting index to search from (beginning at this index, searching to the last element in the array), if start index not provided searches from the first element. If the value is not found in the array returns -1. Also arr.lastIndexOf(value, startIndex) works same way, returning index of the final instance of the value.

arr.includes(value, startIndex)

Checks whether an array includes the provided value. Returns a boolean. Optional second parameter gives the position of the index of where to start the search from, same as indexOf().

arr.some(testFunction)

Tests whether any element within the array returns a truthy value based on the provided test. Returns a boolean.

arr.every(testFunction)

Tests whether every element in the array returns a truthy value based on the provided test. Returns a boolean.

Sorting and iterating through arrays:

arr.reverse()

Reverses the order of the elements in the array. Mutates original array, return value is reversed array.

arr.sort(compareFunction)

Sorts elements in array based on function provided. If no compare function provided will convert elements into strings and sort based on UTF-16 code values, which can result in some unexpected behaviour with non-string elements, so unless sorting an array of strings you should to provide a sort function:

  • To sort numbers ascending use: arr.sort((a, b) => a - b)
  • To sort numbers descending use: arr.sort((a, b) => b - a)

Mutates original array, return value is sorted array.

arr.Map(function)

Applies the provided function to each of the elements in the array, and pushes these into values into a new array. eg [1,2,3].map( x => x * 2 ) returns [2,4,6]. Non-destructive, return value is mutated copy of original array.

arr.reduce(function(total, currentValue), initialValue)

Reduces array to a single value by iterating through elements and applying the provided function to each element, accumulating the changes in each iteration. The function parameter must be provided a minimum of two arguments — the total, which is the starting value at the first iteration, and and the current value which is the value of the current element in the array. On each iteration the value of total changes by applying the function to the current value. In addition to a function, reduce takes an optional second argument of an initial value, which will be provided to the function as the value of total on the first iteration . If not set initialValue will default to 0 but can result in unintended behaviours, so it is safest to always specify an initial value. The return value is the value of total after the function has been called on the final element in the array. See the docs for a more thorough explanation and details on the additional possible arguments for the function parameter.

arr.reduceRight(function(total, currentValue), initialValue)

Works exactly the same as reduce() but applies it to the elements in the array from right to left (ie starts from the final element, iterating backwards through the array to the first element).

Links to the rest of the Getting To Know JavaScript Built-In Methods series:

--

--

Tolani Benson
The Startup

Ex-financial analyst turned software engineer. Lover of learning, coding, cake and dogs. Not in that order.