Array Methods in JavaScript

Before going into all the methods present to work on an Array, let's understand what an Array first...

What is an Array?

  1. In JavaScript, an array is a data structure that contains a list of elements that store multiple values in a single variable.
  2. Arrays provide a lot of methods to perform traversal and mutation operations.
  3. Neither the length of a JavaScript array nor the types of its elements are fixed.
  4. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array.

There are many useful built-in properties and methods that will help you resolve any task which involves arrays. Array methods are functions built-in to JavaScript that we can apply to our arrays — Each method has a unique function that performs a change or calculation to our array and saves us from writing common functions from scratch.

So, without further ado, let's get started...

Array Methods

1. Array.sort()

  1. The sort() method sorts the elements of an array in place and returns the sorted array.
  2. The default sort() method converts the element types into strings and then sorts them.
  3. The default sorting order is ascending.
  4. The sort() method changes the original array.
  5. If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.

Syntax:

// Functionless
sort()

// Arrow function
sort((firstEl, secondEl) => { ... } )

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(firstEl, secondEl) { ... })

Examples:

const array = ["orange","blue","yellow","black","white"];
console.log(array.sort());
// Output:
[ 'black', 'blue', 'orange', 'white', 'yellow' ]

const array2 = [2,321,100,1310,43];
console.log(array2.sort());
// Output:
[ 100, 1310, 2, 321, 43 ]

console.log(array2.sort((firstEle, secondEle) => {
  return firstEle - secondEle;
}));
// Output:
[ 2, 43, 100, 321, 1310 ]

2. Array.splice()

  1. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
  2. To add an element using the splice() method, we need to pass the position where we want to add, how many elements to delete starting with the position, and the element to add.
  3. If the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed.
  4. An array containing the deleted elements.
  5. If only one element is removed, an array of one element is returned.
  6. If no elements are removed, an empty array is returned.

Syntax:

splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)

Examples:

Remove 0 (zero) elements before index 2, and insert "drum"

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum')

// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed

Remove 1 element at index 3

let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1)

// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

let myFish = ['angel', 'clown', 'trumpet', 'sturgeon']
let removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue')

// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]

3. Array.some()

  1. The some() method tests whether at least one element in the array passes the test implemented by the provided function.
  2. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.
  3. It doesn't modify the array.
  4. callbackFn is invoked only for indexes of the array with assigned values. It is not invoked for indexes that have been deleted or which have never been assigned values.
  5. callbackFn is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.
  6. Calling some() on an empty array returns false for any condition!

Syntax:

// Arrow function
some((element) => { ... } )
some((element, index) => { ... } )
some((element, index, array) => { ... } )

// Callback function
some(callbackFn)
some(callbackFn, thisArg)

// Inline callback function
some(function callbackFn(element) { ... })
some(function callbackFn(element, index) { ... })
some(function callbackFn(element, index, array){ ... })
some(function callbackFn(element, index, array) { ... }, thisArg)

Examples:

Testing value of array elements

const arr = [1, 2, 3, 4, 5, 6, 7];

const greaterThan5 = arr.some((e) => e > 5);
console.log(greaterThan5); // true

const lessNum = arr.some((e) => e <= 0);
console.log(lessNum); // false

4. Array.shift()

  1. The shift() method removes the first element from an array and returns that removed element.
  2. This method changes the length of the array.
  3. The shift() removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

Syntax:

shift()

Examples:

Removing an element from an array

const arr = ["2", "1", "2", "3", "4"];

console.log(arr.shift()); // 2

console.log(arr); // [ '1', '2', '3', '4' ]

5. Array.slice()

  1. The slice() returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
  2. The original array will not be modified.

Syntax:

slice()
slice(start)
slice(start, end)

Examples:

Return a portion of an existing array

const arr = ["a", "b", "c", "d", "e"];

const sliced = arr.slice(2, 4);

const slice = arr.slice(1);

console.log(sliced); // [ 'c', 'd' ]

console.log(slice); // [ 'b', 'c', 'd', 'e' ]

console.log(arr); // [ 'a', 'b', 'c', 'd', 'e' ]

6. Array.reverse()

  1. The reverse() reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

Syntax:

reverse()

Examples:

Reversing the elements in an array

const arr = [1, 2, 3, 4, 5];

console.log(arr.reverse()); // [ 5, 4, 3, 2, 1 ]

const arr1 = ["sam", "cole", "heith"];

console.log(arr1.reverse()); // [ 'heith', 'cole', 'sam' ]

7. Array.reduce()

  1. reduce() applies a function against an accumulator and each element in the array to reduce it to a single value.

Syntax:

// Arrow function
reduce((accumulator, currentValue) => { ... } )
reduce((accumulator, currentValue, index) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function callbackFn(accumulator, currentValue) { ... })
reduce(function callbackFn(accumulator, currentValue, index) { ... })
reduce(function callbackFn(accumulator, currentValue, index, array){ ... })
reduce(function callbackFn(accumulator, currentValue, index, array) { ... }, initialValue)

The reduce() executes the callbackFn once for each assigned value present in the array, taking four arguments:

  • accumulator
  • currentValue
  • currentIndex
  • array

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then the accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then the accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

Examples:

Sum all the values of an array

const arr = [1, 2, 3, 4, 5, 6];

const reduced = arr.reduce((total, element) => total + element);

console.log(reduced); // 21

Sum of values in an object array

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x
}, initialValue)

console.log(sum) // 6

8. Array.map()

The map() calls the specified function for every array element and returns the new array

Syntax:

// Arrow function
map((element) => { ... } )
map((element, index) => { ... } )
map((element, index, array) => { ... } )

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function callbackFn(element) { ... })
map(function callbackFn(element, index) { ... })
map(function callbackFn(element, index, array){ ... })
map(function callbackFn(element, index, array) { ... }, thisArg)

It is not called for missing elements of the array; that is:

  • indexes that have never been set;
  • indexes which have been deleted.

You shouldn't be using map() if:

  • You're not using the array it returns; and/or
  • You're not returning a value from the callback.

Examples:

Mapping an array of numbers to an array of their squares

const arr = [1, 2, 3, 4, 5, 6];

const mapped = arr.map((e) => e * 2);

console.log(mapped); // [ 2, 4, 6, 8, 10, 12 ]

9. Array.indexOf()

  1. The indexOf() returns the first index at which a given element can be found in the array, or -1 if it is not present.
  2. indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

Syntax:

indexOf(searchElement)
indexOf(searchElement, fromIndex)

fromIndex -> The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array.

Note: If the provided index is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched).

Examples:

Using indexOf()

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

Finding all the occurrences of an element

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

10. Array.includes()

  1. You can determine the presence of an element in an array using the includes().
  2. If the element is found, the method returns true, and false otherwise.

Syntax:

includes(searchElement)
includes(searchElement, fromIndex)
  1. The position in this array at which to begin searching for searchElement.
  2. The first element to be searched is found at fromIndex for positive values of fromIndex, or at arr.length + fromIndex for negative values of fromIndex (using the absolute value of fromIndex as the number of elements from the end of the array at which to start the search).
  3. Defaults to 0.

Examples:

const names = ['tom', 'alex', 'bob', 'john'];

names.includes('tom'); // true
names.includes('july'); // false

Examples:

fromIndex is greater than or equal to the array length

let arr = ['a', 'b', 'c']

arr.includes('c', 3)    // false
arr.includes('c', 100)  // false

11. Array.forEach()

  1. forEach() is used to loop over array by executing a provided callback for each element in an array

Syntax:

// Arrow function
forEach((element) => { ... } )
forEach((element, index) => { ... } )
forEach((element, index, array) => { ... } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function callbackFn(element) { ... })
forEach(function callbackFn(element, index) { ... })
forEach(function callbackFn(element, index, array){ ... })
forEach(function callbackFn(element, index, array) { ... }, thisArg)

Examples:

No operation for uninitialized values (sparse arrays)

const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach(function(element) {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.

Converting a for loop to forEach

const items = ['item1', 'item2', 'item3']
const copyItems = []

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i])
}

// after
items.forEach(function(item){
  copyItems.push(item)
})

12. Array.findIndex()

  1. The findIndex() returns the index of the first element in the array that satisfies the provided testing function.
  2. Otherwise, it returns -1, indicating that no element passed the test.

Syntax:

// Arrow function
findIndex((element) => { ... } )
findIndex((element, index) => { ... } )
findIndex((element, index, array) => { ... } )

// Callback function
findIndex(callbackFn)
findIndex(callbackFn, thisArg)

// Inline callback function
findIndex(function callbackFn(element) { ... })
findIndex(function callbackFn(element, index) { ... })
findIndex(function callbackFn(element, index, array){ ... })
findIndex(function callbackFn(element, index, array) { ... }, thisArg)

Note:

  1. If the index of the first element in the array that passes the test is 0, the return value of findIndex will be interpreted as Falsy in conditional statements.
  2. Unlike other array methods such as Array.some(), callbackFn is run even for indexes with unassigned values.

Examples:

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

13. Array.find()

  1. The find() returns the value of the first element in the provided array that satisfies the provided testing function.
  2. If no values satisfy the testing function, undefined is returned.

Syntax:

// Arrow function
find((element) => { ... } )
find((element, index) => { ... } )
find((element, index, array) => { ... } )

// Callback function
find(callbackFn)
find(callbackFn, thisArg)

// Inline callback function
find(function callbackFn(element) { ... })
find(function callbackFn(element, index) { ... })
find(function callbackFn(element, index, array){ ... })
find(function callbackFn(element, index, array) { ... }, thisArg)

Examples:

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

Note:

  1. If you need the index of the found element in the array, use findIndex().
  2. If you need to find the index of a value, use Array.prototype.indexOf(). (It’s similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
  3. If you need to find if a value exists in an array, use Array.prototype.includes(). Again, it checks each element for equality with the value instead of using a testing function.
  4. If you need to find if any element satisfies the provided testing function, use Array.prototype.some().

17. Array.filter()

  1. The filter() creates a new array with all elements that pass the test implemented by the provided function.

Syntax:

// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
filter(function callbackFn(element, index, array) { ... }, thisArg)

Examples:

const arr = [1, 2, 3, 4, 5, 6];

const filtered = arr.filter((e) => e === 2 || e === 4);

console.log(filtered); // [ 2, 4 ]

Find all prime numbers in an array

const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i == 0) {
      return false;
    }
  }
  return num > 1;
}

console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

18. Array.fill()

  1. The fill() changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length).
  2. It returns the modified array.

Syntax:

fill(value)
fill(value, start)
fill(value, start, end)

Examples:

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

Note:

  1. If start is negative, it is treated as array.length + start.
  2. If end is negative, it is treated as array.length + end.
  3. fill is intentionally generic: it does not require that it's this value be an Array object.
  4. fill is a mutator method: it will change the array itself and return it, not a copy of it.
  5. If the first parameter is an object, each slot in the array will reference that object.

19. Array.every()

  1. The every() tests whether all elements in the array pass the test implemented by the provided function.
  2. It returns a Boolean value.

Syntax:

// Arrow function
every((element) => { ... } )
every((element, index) => { ... } )
every((element, index, array) => { ... } )

// Callback function
every(callbackFn)
every(callbackFn, thisArg)

// Inline callback function
every(function callbackFn(element) { ... })
every(function callbackFn(element, index) { ... })
every(function callbackFn(element, index, array){ ... })
every(function callbackFn(element, index, array) { ... }, thisArg)

Examples:

const arr = [3, 5, 8, 2, 10, 33];

const greaterThan5 = arr.every((e) => e > 5);
console.log(greaterThan5); // false

const lessThan40 = arr.every((e) => e < 40);
console.log(lessThan40); // true

20. Array.copyWithIn()

  1. The copyWithin() shallow copies part of an array to another location in the same array and returns it without modifying its length.

Syntax:

copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)

Examples:

const array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]

Conclusion

I have tried to cover some of the Array methods, but there are a lot more to go. If you want to know more and in-depth about Array methods the only goto place that comes up to my mind is MDN - Array

Hoping to make some more blogs on Polyfill for the Array methods next. I hope, you liked it.