/
/
30 Useful JavaScript Array Methods You Must Know
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email

30 Useful JavaScript Array Methods You Must Know

One of the most powerful building blocks built into the JavaScript language is arrays. An array is an object that can store a collection of items. Arrays become useful when you need to store large amounts of data of the same type. Suppose you want to store the details of 100 students. If you are using variables, you will need to create 100 variables. But you can do the same with a single array. You can access the items in an array by referring to its index number, and the index of the first element of an array is zero.

What Are Array Methods?

Arrays have many properties and methods of use, which helps developers handle them easily and efficiently. Array methods are functions built into JavaScript that you can apply to your arrays. Each method has a unique function that performs a change or calculation on your array, saving you from needing to code common functions from scratch.Array methods in JavaScript are run using a dot-notation attached to the array variable. Since they’re just JavaScript functions, they always end with a parenthesis, which can hold optional arguments. In this post, we will discuss 30 array methods in detail with examples.

1. concat()

This method is used to merge two or more arrays

  • Syntaxarray1.concat(array2, array3, …, arrayX)
  • Parametersarray2, array3, …, arrayX(Optional)

These are arrays or values to concatenate into a new array. If all the parameters are omitted, concat returns a shallow copy of the existing array on which it is called.

  • Return value – A new array instance.

Note: This method does not change the existing arrays, but instead returns a new array.Examples:
const array1 = ['a', 'b', 'c'];const array2 = ['d', 'e', 'f'];const array3 = array1.concat(array2);
console.log(array3);// expected output: Array ["a", "b", "c", "d", "e", "f"]
const array1 = ['a', 'b', 'c'];const array2 = array1.concat();
console.log(array2);// expected output: Array ["a", "b", "c"]

2. copyWithin()

This method copies the part of the given array with its own elements and returns the modified array. It copies elements of an array from within the same array. This method will never add more items to the array.

  • Syntaxarray.copyWithin(target, start, end)
  • Parameters – This method accepts three parameters as mentioned above and described below:  
  • target(Required): The index position to copy the elements to.
  • start(Optional): The index position to start copying elements from (default is 0).
  • end(Optional):  The index position to stop copying elements from (default is array.length). copyWithin() copies up to but not including end.
  • Return value – The modified array.

Note: If you have a negative index,  the target will be counted from the end, the start will be counted from the end, and the end will be counted from the end. Or change the index to array.length + negTarget, array.length + negStart and array.length + negEnd. Examples:
[1, 2, 3, 4, 5].copyWithin(0, 3)// [4, 5, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)// [4, 2, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(-2) // [1, 2, 3, 1, 2]// [1, 2, 3, 4, 5].copyWithin(5-2)// [1, 2, 3, 4, 5].copyWithin(3) - [1, 2, 3, 1, 2]
[1, 2, 3, 4, 5].copyWithin(-2, -3, -1) // [1, 2, 3, 3, 4]// [1, 2, 3, 4, 5].copyWithin(5-2, 5-3, 5-1)// [1, 2, 3, 4, 5].copyWithin(3, 2, 4) - [1, 2, 3, 3, 4]

3. entries()

This method returns a new array iteratorobject that contains the key/value pairs for each index in the array.

  • Syntaxarray.entries()
  • Parameters – This method does not accept any parameters
  • Return value – A new array iterator object

Note: This method does not change the original array.Examplesa) Iterating with index and element
const array1 = ['x', 'y', 'z'];
for (const [index, element] of array1.entries())  console.log(index, element);
// 0 'x'// 1 'y'// 2 'z'
b) Using a for … of loop
const array2 = ['x', 'y', 'z'];const iterator = array2.entries();for (let e of iterator) {  console.log(e);}// [0, 'x']// [1, 'y']// [2, 'z']
c) Using next and value 
const array3 = ['x', 'y', 'z'];const iterator1 = array3.entries();
console.log(iterator1.next().value);// expected output: Array [0, "x"]console.log(iterator1.next().value); // expected output: Array [1, "y"]console.log(iterator1.next().value); // expected output: Array [2, "z"]

4. every()

This method checks whether all the elements of the array satisfy the condition provided by a method passed to it as the argument. This method will return true if all the elements pass the set. If an element is found not to satisfy the condition, the method returns false.

  • Syntaxarray.every(function(currentValue, index, arr), thisValue)
  • Parameters – This method accepts five parameters as mentioned above and described below:
  • callback: This parameter holds the function to be called for each element of the array.
    • currentValue: The parameter holds the value of the elements being processed currently.
    • index (Optional): It holds the index of the currentValue element in the array starting from 0.
    • arr (Optional): It holds the complete array on which Array.every is called.
  • thisValue(Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value – A Boolean. It returns true if all the elements in the array pass the test; otherwise, it returns false.

Note: This method does not execute the function for array elements without values. This method does not change the original array.Examples
function ispositive(element, index, array) {  return element > 0;}console.log([10, 39, 23, 47, 8].every(ispositive));//true
function isodd(element, index, array) {  return (element % 2 == 1);}console.log([56, 41, 18, 82, 14].every(isodd));// false

5. fill()

This method is used to fill the array with a given static value. The value can be used to fill the entire array, or it can be used to fill a part of the array.

  • Syntaxarray.fill(value, start, end)
  • Parameters – This method accepts three parameters as mentioned above and described below:
  • value: It defines the static value with which the array elements are to be replaced.
  • start(Optional): It defines the starting index from where the array is to be filled with the static value. If this value is not defined, the starting index is taken as 0. If the start is negative, then the net start index is length+start.
  • end(Optional): This argument defines the last index up to which the array is to be filled with the static value. If this value is not defined, then the last index of the array, i.e., arr.length, is taken as the end value by default. If the end is negative, then the net end is defined as length+end.
  • Return value – This method does not return a new array. Instead, it modifies the array on which this method is applied.

Note: This method overwrites the original array.Examples:
const array1 = [1, 2, 3, 4];
//fill with 0 from position 2 until position 4console.log(array1.fill(0, 2, 4));// expected output: [1, 2, 0, 0]
//fill with 5 from position 1console.log(array1.fill(5, 1));// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));// expected output: [6, 6, 6, 6]
const array2 = [1, 23, 46, 98];console.log(array2.fill(82, 1, 3));// expected output: [1, 82, 82, 98]

6. filter()

This method creates a new array with all the elements that pass the test implemented by the provided function.

  • Syntaxarray.filter(function(currentValue, index, arr), thisValue)
  • Parameters – This method accepts five parameters as mentioned above and described below: 
  • callback: This parameter holds the function to be called for each element of the array.
    • currentValue: The parameter holds the value of the element being processed currently.
    • index(Optional): It holds the index of the currentValue element in the array starting from 0.
    • arr(Optional):  It holds the complete array on which Array.every is called.
  • thisValue(Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value – A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.

Note: This method does not execute the function for array elements without values. Also, this method does not change the original array.Examples:function isEven(value) {  return value % 2 == 0;}
const filtered = [13, 98, 37, 23, 924].filter(isEven);console.log(filtered);// expected output: [98,924]

function isPositive(value) {  return value > 0;}
const filtered = [102, 42, 0, -4, 944].filter(isPositive);console.log(filtered);// expected output:  [102, 42, 944]

7. find() 

This method returns the value of the first element in the provided array that satisfies the provided testing function. If no value satisfies the testing function, undefined is returned.

  • Syntaxarray.find(function(currentValue, index, arr),thisValue)
  • Parameters -This method accepts five parameters as mentioned above and described below:
  • function: It is the function of the array that works on each element.
    • currentValue: This parameter holds the current element.
    • index(Optional): It holds the index of the current element.
    • arr(Optional): It holds the array object to which the current element belongs.
  • thisValue(Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value – The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Note: This method does not execute the function for empty arrays. Also, it does not change the original array.Examples:
const array1 = [5, 12, 80, 140, 45];
const found = array1.find(element => element > 10);
console.log(found);// expected output: 12
const inventory = [  {name: 'apples', quantity: 2},  {name: 'mango', quantity: 7},  {name: 'cherries', quantity: 10}];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result); //  expected output: { name: 'cherries', quantity: 10 }

8. findIndex()

This method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

  • Syntaxarray.findIndex(function(currentValue, index, arr), thisValue)
  • Parameters -This method accepts five parameters as mentioned above and described below:
  • function: It is the function of the array that works on each element.
    • currentValue: This parameter holds the current element.
    • index(Optional): It holds the index of the current element.
    • arr (Optional): It holds the array object to which the current element belongs.
  • thisValue (Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value-The index of the first element in the array that passes the test. If none pass, it returns as -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.

Note: This method does not execute further once it finds an element satisfying the testing method. Also, this method does not change the original array.Examples:const array1 = [7, 11, 8, 137, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));// expected output: 3 
const fruits = ["apple", "banana", "mango", "blueberries", "cherries"];
const index = fruits.findIndex(fruit => fruit === "blueberries");
console.log(index); // 3console.log(fruits[index]); // blueberries

9. flat()

This method creates a new array with all the sub-array elements concatenated into it recursively up to the specified depth.

  • Syntaxarray.flat(depth)
  • Parameters – depth: The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
  • Return value – A new array with the sub-array elements concatenated into it.

Note: This method does not change the original array.Examples:
const array1 = [1, 2, [3, 4]];console.log(array1.flat());// [1, 2, 3, 4]
const array2 = [1, 2, [3, 4, [5, 6]]];console.log(array2.flat());// [1, 2, 3, 4, [5, 6]]
const array3 = [1, 2, [3, 4, [5, 6]]];console.log(array3.flat(2));// [1, 2, 3, 4, 5, 6]
When you don’t know the depth level, you can pass the Infinity into the flat() method to recursively concatenate all the elements of the sub-arrays into the new array:
const array4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];console.log(array4.flat(Infinity));// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If an array has empty slots, you can use the flat() method to remove the holes, like this:
const array5 = [1, 2, , 4, 5];console.log(array5.flat());// [1, 2, 4, 5]

10. forEach()

This method calls a function once for each element in an array, in order. The provided function may perform any kind of operation on the elements of the given array.

  • Syntaxarray.forEach(function(currentValue, index, arr), thisValue)
  • Parameters -This method accepts five parameters as mentioned above and described below:
  • callback: This parameter holds the function to be called for each element of the array.
    • currentValue: The parameter holds the value of the element being processed currently.
    • index(Optional): It holds the index of the current value element in the array starting from 0.
    • array(Optional): It holds the complete array on which Array.every is called.
  • thisValue(Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value – The return value of this method is always undefined. This method may or may not change the original array provided because it depends upon the functionality of the argument function.

Note: The function is not executed for array elements without values.Examples:
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"// expected output: "b"// expected output: "c"
const items = [1, 25, 45];const copy = [];
items.forEach(function(item){  copy.push(item*item);});console.log(copy);// expected output: [1, 841, 2209]

11. from()

This method is used to create a new array instance from a given array. In the case of a string, the string’s every alphabet is converted into an element of the new array instance, and in the case of integer values, a new array instance takes the elements of the given array.

  • Syntax – Array.from(object, mapFunction, thisValue)
  • Parameters – This method accepts three parameters as mentioned above and described below:
  • object: This parameter holds the object that will convert into an array
  • mapFunction(Optional): It is used to call on each item of the array.
  • thisValue(Optional): It holds the value to use as this when executing the mapFunction.
  • Return value – A new Array instance.

Examples:
console.log(Array.from('javascript'));// expected output: Array ["j", "a", "v", "a", "s", "c", "r", "i", "p", "t",]
console.log(Array.from([1, 2, 3, 4], x => x + x));// expected output: Array [2, 4, 6, 8]

const set = new Set(['foo', 'bar', 'baz', 'foo', 'bar']);console.log(Array.from(set));// [ "foo", "bar", "baz" ]
function f() {  return Array.from(arguments);}
console.log(f(1, 2, 3, 4, 5));
// [ 1, 2, 3, 4, 5 ]

12. includes()

This method determines whether an array contains a specified element. This method returns true if the array contains the element and false if not.

  • Syntaxarray.includes(searchElement,fromIndex)
  • Parameters – This method accepts two parameters as mentioned above and described below:
  • searchElement: The value to search for.
  • fromIndex(Optional): The position in this array at which to begin searching for searchElement. 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. It defaults to 0.
  • Return value – A Boolean, which is true if the value searchElement is found within the array (or the part of the array indicated by the index fromIndex, if specified).

Note: This method is case sensitive.Examples:
const array1 = [1, 2, 3, 4, 5];
console.log(array1.includes(2));// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('bat'));// expected output: true
console.log(pets.includes('at'));// expected output: false
console.log([1, 2, 3, 4, 5].includes(2));      // trueconsole.log([1, 2, 3, 4, 5].includes(6));      // falseconsole.log([1, 2, 3, 4, 5].includes(3, 3));   // falseconsole.log([1, 2, 3, 4, 5].includes(5, -1));  // trueconsole.log([1, 2, NaN, 4, 5].includes(NaN));  // true

  1. fromIndex is greater than or equal tothearraylength – If fromIndex is greater than or equal to the length of the array, it returns as false. The array will not be searched.

const array2 = ['a', 'b', 'c', 'd',];
console.log(array2.includes('c', 3));    // falseconsole.log(array2.includes('c', 100));  // false 

  1. Computed index is less than 0 – If fromIndex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for the searchElement. If the computed index is less than or equal than -1 * arr.length, the entire array will be searched.

// array3 length is 4// fromIndex is -100// computed index is 4 + (-100) = -96
const array3 = ['a', 'b', 'c', 'd'];
console.log(array3.includes('a', -100)); // trueconsole.log(array3.includes('b', -100)); // trueconsole.log(array3.includes('c', -100)); // trueconsole.log(array3.includes('a', -2));   // false

13. indexOf()

This method returns the first index at which a given element can be found in the array, or -1 if it is not present.

  • Syntaxarray.indexOf(element, start)
  • Parameters – This method accepts two parameters as mentioned above and described below:
  • element: This parameter holds the element of which the index will be returned.
  • start(Optional): It holds the starting point of the array, where the search is to begin; the default value is 0.  If the provided index value is a negative number, it is taken as the offset from the end of the array. If the provided start is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched.
  • Return value  – The first index of the element in the array; -1 if not found.

Note: The first item has position 0, the second item has position 1, and so on. If you want to search from end to start, use the lastIndexOf() method.Examples:
const colors = ['red', 'black', 'brown', 'green', 'black'];
console.log(colors.indexOf('black'));// expected output: 1
// start from index 2console.log(colors.indexOf('black', 2));// expected output: 4
console.log(colors.indexOf('yellow'));// expected output: -1
// still start from index 2console.log(colors.indexOf('black', -2));// expected output: 4
const array = [2, 7, 7];
console.log(array.indexOf(2));     // 0console.log(array.indexOf(6));     // -1console.log(array.indexOf(7, 2));  // 2console.log(array.indexOf(2, -1)); // -1console.log(array.indexOf(2, -3)); // 0

14. isArray() 

This method determines whether the value passed to this function is an array or not. This function returns true if the argument passed is an array; else, it returns false.

  • Syntax – Array.isArray(obj)
  • Parameters – This method accepts a single parameter as mentioned above and described below:
  • obj: This parameter holds the object that will be tested.
  • Return value  – A Boolean. It returns true if the object is an array; otherwise, it returns false.

Examples:
//all following calls return trueconsole.log(Array.isArray([]));console.log(Array.isArray([1]));console.log(Array.isArray(new Array()));console.log(Array.isArray(new Array('a', 'b', 'c', 'd','e')));console.log(Array.isArray(new Array(3)));// Little known fact: Array.prototype itself is an array:console.log(Array.isArray(Array.prototype));
//all following calls return falseconsole.log(Array.isArray());console.log(Array.isArray({}));console.log(Array.isArray(null));console.log(Array.isArray(undefined));console.log(Array.isArray(13));console.log(Array.isArray('Array'));console.log(Array.isArray(true));console.log(Array.isArray(false));console.log(Array.isArray(new Uint8Array(32)));console.log(Array.isArray({ __proto__: Array.prototype }));

15. join() 

This method creates and returns a new string by concatenating all the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

  • Syntaxarray.join(separator)
  • Parameters –  This method accepts a single parameter as mentioned above and described below:
  • separator(Optional):It can be either used as a parameter or not. Its default value is comma (,).
  • Return value  – A string representing the array values, separated by the specified separator. If arr.length is 0, an empty string is returned.

Note: This method will not change the original array.Examples:
const array1 = ['Wind', 'Water', 'Fire'];console.log(array1.join());      // 'Wind,Water,Fire'console.log(array1.join(', '));  // 'Wind, Water, Fire'console.log(array1.join(' + ')); // 'Wind + Water + Fire'console.log(array1.join(''));    // 'WindWaterFire'

const array2 = [1, 2, 3, 4, 5, 6];console.log(array2.join('|'));// 1|2|3|4|5|6
console.log(array2.join());// 1, 2, 3, 4, 5, 6console.log(array2.join(' '));// 1 2 3 4 5 6
function f(a, b, c) {  const s = Array.prototype.join.call(arguments);  console.log(s); // '1,a,b,true'}console.log(f(1, 'a', 'b', true));//expected output: "1,a,b,true"

16. keys() 

This method is used to return a new array iterator that contains the keys for each index in the given input array.

  • Syntaxarray.keys()
  • Parameters –  This method does not accept any parameters.
  • Return value  – A new array iterator object.

Note: This method does not change the original array.Examples:
const array1 = ['x', 'y', 'z'];const iterator = array1.keys();
for (const key of iterator) {  console.log(key);}
// expected output: 0// expected output: 1// expected output: 2
Key iterator doesn’t ignore holes:const arr = ['x', , 'z'];const sparseKeys = Object.keys(arr);const denseKeys = [...arr.keys()];console.log(sparseKeys); // ['0', '2']console.log(denseKeys);  // [0, 1, 2]

17. map() 

This method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. This method is used to iterate over an array and call a function on every element of the array.

  • Syntaxarray.map(function(currentValue, index, arr), thisValue)
  • Parameters – This method accepts two parameters as mentioned above and described below:
  • function(currentValue, index, arr): It is a required parameter, and runs on each element of the array. It contains three parameters that are listed below:
    • currentValue (Required): It holds the value of the current element.
    • index(Optional): It holds the index of the current element.
    • arr(Optional): It holds the array.
  • thisValue(Optional): It is used to hold the value passed to the function.
  • Return value  – An array containing the results of calling the provided function for each element in the original array.

Note: This method does not execute the function for array elements without values.Examples
const array1 = [1, 4, 9, 16, 25];
// pass a function to mapconst map1 = array1.map(x => x * 2);
console.log(map1);// expected output: Array [2, 8, 18, 32, 50]
const numbers = [1, 4, 9]const roots = numbers.map(function(num) {    return Math.sqrt(num);});// roots is now     [1, 2, 3]// numbers is still [1, 4, 9]
const kvArray = [{key: 1, value: 10}, {key: 2, value: 20},                 {key: 3, value: 30}]
const reformattedArray = kvArray.map(obj => {   let rObj = {};   rObj[obj.key] = obj.value;   return rObj;});// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
// kvArray is still:// [{key: 1, value: 10},//  {key: 2, value: 20},//  {key: 3, value: 30}]

18. of() 

This method creates a new array instance from a variable number of arguments, regardless of the number or type of the arguments.

  • Syntax – Array.of(element0, element1, … , elementN)
  • Parameters –  elementN: Elements used to create the array
  • Return value  – A new array instance.

Examples:
console.log(Array.of(7)); // [7]console.log(Array(7)); // array of 7 empty slots
console.log(Array.of(1, 2, 3)); // [1, 2, 3]console.log(Array(1, 2, 3));    // [1, 2, 3]
console.log(Array.of(1));         // [1]console.log(Array.of(undefined)); // [undefined]

19. pop() 

This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1.

  • Syntaxarray.pop()
  • Parameters –  This method does not accept any parameters.
  • Return value  – The removed element from the array; undefined if the array is empty.

Note:  This method changes the length of an array.Examples:

  1. Removing the last element of an array

const colors = ['red', 'black', 'brown', 'blue', 'green'];
console.log(colors.pop());// expected output: "green"
console.log(colors);// expected output: Array ["red", "black", "brown", "blue"]
colors.pop();
console.log(colors);// expected output: Array ["red", "black", "brown"]
The following code creates the myFish array containing four elements. Then it removes its last element.const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
const popped = myFish.pop();console.log(myFish); // ['angel', 'clown', 'mandarin' ]
console.log(popped); // 'sturgeon'

  1. Using apply( ) or call( ) on array-like objects

The following code creates the myFish array-like object containing four elements and a length parameter. Then it removes its last element and decrements the length parameter.const myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4};
const popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )
console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3}
console.log(popped); // 'sturgeon'

20. push() 

This method adds one or more elements to the end of an array and returns the new length of the array.

  • Syntaxarray.push(item1, item2, …, itemX)
  • Parameters –  item1, item2, …, itemX:This method contains as many numbers of parameters as the number of elements to be inserted into the array.
  • Return value  – A number, representing the new length of the array.

Note: The new item(s) will be added at the end of the array. This method changes the length of the array.Examples:
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');console.log(count);// expected output: 4console.log(animals);// expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');console.log(animals);// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
const sports = ['soccer', 'baseball']const total = sports.push('football', 'swimming')
console.log(sports);  // ['soccer', 'baseball', 'football', 'swimming']console.log(total); // 4
const vegetables = ['parsnip', 'potato']const moreVegs = ['celery', 'beetroot']
// Merge the second array into the first one// Equivalent to vegetables.push('celery', 'beetroot')Array.prototype.push.apply(vegetables, moreVegs)
console.log(vegetables);// ['parsnip', 'potato', 'celery', 'beetroot']

21. reduce() 

This method in JavaScript is used to reduce the array to a single value. It executes a provided function for each value of the array (from left-to-right), and then the return value of the function is stored in an accumulator.

  • Syntaxarray.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • Parameters –  This method accepts five parameters as mentioned above and described below:
  • function(total, currentValue, currentIndex, arr): It is the required parameter and run for each element of the array. It contains four parameters, which are listed below:
    • total (Required): It is used to specify the initialValue or the previously returned value of the function.
    • currentValue(Required): It is used to specify the value of the current element.
    • currentIndex(Optional): It is used to specify the array index of the current element.
    • arr (Optional): It is used to specify the array object to which the current element belongs.
  • initialValue(Optional): It specifies the value to be passed to the function as the initial value.
  • Return value  – The single value that results from the reduction.

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0. This method does not execute the function for array elements without values. Also, this method does not change the original array.Examples:const array1 = [1, 2, 3, 4, 5];const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4 + 5console.log(array1.reduce(reducer));// expected output: 15
// 5 + 1 + 2 + 3 + 4 + 5 + 6console.log(array1.reduce(reducer, 6));// expected output: 21
const getMax = (a, b) => Math.max(a, b);
// callback is invoked for each element in the array starting at index 0console.log([1, 100].reduce(getMax, 50)); // 100console.log([    50].reduce(getMax, 10)); // 50
// callback is invoked once for element at index 1console.log([1, 100].reduce(getMax));     // 100
// callback is not invokedconsole.log([    50].reduce(getMax));     // 50console.log([      ].reduce(getMax, 1));  // 1
console.log([      ].reduce(getMax));     // TypeError

22. reverse()

This method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

  • Syntaxarray.reverse()
  • Parameters –  This method does not accept any parameters.
  • Return value  – This method returns the reference of the reversed original array.

Note: This method will change the original array.Examples:

  1. Reversing the elements in an array

const numbersArray = ['one', 'two', 'three'];
const reversed = numbersArray.reverse();console.log('reversed:', reversed);// expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.console.log('numbersArray:', numbersArray);// expected output: "numbersArray:" Array ["three", "two", "one"] The following example creates an array, array1, containing three elements, then reverses the array. The call to reverse() returns a reference to the reversed array a.const array1 = [1, 2, 3];console.log(array1); // [1, 2, 3]
array1.reverse();console.log(array1); // [3, 2, 1] 

  1. Reversing the elements in an array-like object

The following example creates an array-like object obj, containing three elements and a length property, then reverses the array-like object. The call to reverse() returns a reference to the reversed array-like object obj.const obj = {0: 1, 1: 2, 2: 3, length: 3};
console.log(obj); // {0: 1, 1: 2, 2: 3, length: 3}
Array.prototype.reverse.call(obj); //same syntax for using apply()
console.log(obj); // {0: 3, 1: 2, 2: 1, length: 3}

23. shift()

This method removes the first element from an array and returns that removed element. This method changes the length of the array.

  • Syntaxarray.shift()
  • Parameters – This method does not accept any parameters.
  • Return value – The removed element from the array; undefined if the array is empty.

Note: This method will change the original array.Examples:const array1 = [1, 2, 3, 4, 5];
const firstElement = array1.shift();
console.log(array1);// expected output: Array [2, 3, 4, 5]
console.log(firstElement);// expected output: 1
The shift() method is often used inside while loop condition. In the following example, every iteration will remove the next element from an array, until it is empty:
const numbersArray = ["one", "two", "three", "four" ,"five"];
while( typeof (i = numbersArray.shift()) !== 'undefined' ) { console.log(i);}// one, two, three, four, five

const arr = [];const value  = arr.shift();console.log(arr); // []console.log(value); // undefined

24. slice() 

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

  • Syntaxarray.slice(start, end)
  • Parameters –  This method accepts two parameters as mentioned above and described below:
  • begin: This parameter defines the starting index from where the portion is to be extracted. If this argument is missing, then the method takes the beginning as 0 as it is the default start value.
  • end: This parameter is the index up to which the portion is to be extracted (excluding the end index). If this argument is not defined, then the array till the end is extracted as it is the default end value. If the end value is greater than the length of the array, then the end value changes to the length of the array.
  • Return value  – A new array containing the extracted elements.

Note: The original array will not be changed.Examples:const colors = ['red', 'black', 'brown', 'blue', 'green'];
console.log(colors.slice(2));// expected output: Array ["brown", "blue", "green"]
console.log(colors.slice(2, 4));// expected output: Array ["brown", "blue"]
console.log(colors.slice(1, 5));// expected output: Array ["black", "brown", "blue", "green"]
const fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']const citrus = fruits.slice(1, 3);console.log(citrus);//expected output: Array ['Orange','Lemon']

25. some()

This method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise, it returns false. It doesn’t modify the array.

  • Syntaxarray.some(function(currentValue, index, arr), thisValue)
  • Parameters –  This method accepts five parameters as mentioned above and described below:
  • callback: This parameter holds the function to be called for each element of the array.
    • currentValue: The parameter holds the value of the elements being processed currently.
    • index(Optional): It holds the index of the currentValue element in the array starting from 0.
    • arr(Optional): It holds the complete array on which Array.every is called.
  • thisValue(Optional): It is the value to be passed to the function to be used as its “this” value. If there is no value, “undefined” is passed as its “this” value.
  • Return value  – A Boolean; true if the callback function returns a truthy value for at least one element in the array. Otherwise, false.

Note: This method does not execute the function for array elements without values. Also, this method does not change the original array.Examples:
const array = [1, 2, 3, 4, 5, 6];
// checks whether an element is evenconst even = (element) => element % 2 === 0;
console.log(array.some(even));// expected output: true
console.log([2, 5, 8, 1, 5].some(x => x > 10));  // falseconsole.log([12, 5, 8, 1, 5].some(x => x > 10)); // true
const fruits = ['apple', 'banana', 'mango', 'orange'];
function checkAvailability(arr, val) {  return arr.some(arrVal => val === arrVal);}
console.log(checkAvailability(fruits, 'guava'));   // falsecheckAvailability(fruits, 'banana'); // true

26. sort()

This method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings and then comparing their sequences of UTF-16 code units values.

  • Syntaxarray.sort(compareFunction)
  • Parameters – This method accepts a single parameter as mentioned above and described below:
  • compareFunction: This parameter is used to sort the elements according to different attributes and in a different order.
    • compareFunction(a,b) < 0
    • Then a comes before b in the answer.
    • compareFunction(a,b) > 0
    • Then b comes before a in the answer.
    • compareFunction(a,b) = 0
    • Then the order of a and b remains unchanged.
    • The function should return a negative, zero, or positive value, depending on the arguments, like function(a, b) {return a-b}
  • Return value – The sorted array. Note that the array is sorted in place, No copy is made.

Note: This method changes the original array.Examples:const months = ['March', 'Jan', 'Feb', 'Dec'];months.sort();console.log(months);// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 32, 4, 29, 1000];array1.sort();console.log(array1);// expected output: Array [1, 1000, 29, 32, 4]
const numbers = [4, 2, 5, 1, 3];numbers.sort((a, b) => a - b);console.log(numbers);
// [1, 2, 3, 4, 5]

27. splice()

This method changes the contents of an array by removing or replacing existing elements and adding new elements in their place.

  • Syntaxarray.splice(index, howmany,item1, ….., itemX)
  • Parameters – This method accepts many parameters. Some of them are described below:
  • index (Required): This parameter is the index that starts modifying the array (with origin at 0). This can be negative also, which begins after that many elements being counted from the end.
  • howmany: The number of elements to be removed from the starting index.
  • items_list: The list of new items separated by comma operators that are to be inserted from the starting index.
  • Return value  – While it mutates the original array in place, it still returns the list of removed items. In case there is no removed array, it returns an empty array.

Note: This method changes the original array.Examples:const months = ['Jan', 'March', 'April', 'June'];months.splice(1, 0, 'Feb');// inserts at index 1console.log(months);// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');// replaces 1 element at index 4console.log(months);// expected output: Array ["Jan", "Feb", "March", "April", "May"]
const colors = ['red', 'black', 'brown', 'green'];const removed = colors.splice(0, 2, 'yellow', 'white', 'blue');
console.log(colors);// ["yellow", "white", "blue", "brown", "green"]
console.log(removed);// ["red", "black"]

28. toString()

This method returns a string with all the array values, separated by commas.

  • Syntaxarray.toString()
  • Parameters – This method does not accept any parameters.
  • Return value – A string, representing the values of the array, separated by a comma.

Note: This method will not change the original array.Examples:
const fruits = ["Banana", "Mango", "Orange", "Apple"];console.log(fruits.toString());//Banana,Mango,Orange,Apple
const array1 = [1, 2, 'a', '1b'];console.log(array1.toString());// expected output: "1,2,a,1b"

29. unshift()

This method adds one or more elements to the beginning of an array and then returns the new length of the array. This function increases the length of the existing array by the number of elements added to the array.

  • Syntaxarray.unshift(item1, item2, …, itemX)
  • Parameters – This method accepts a single parameter.
  • item1, item2, …, itemX(Required):  These parameter elements to be added at the beginning of the array.
  • Return value  – A number, representing the new length of the array.

Note: This method changes the length of an array.Examples:const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));// expected output: 5
console.log(array1);// expected output: Array [4, 5, 1, 2, 3]
const array2 = [1, 2]
console.log(array2.unshift(0));// expected output: 3// array2: [0, 1, 2]
console.log(array2.unshift(-2, -1));          // expected output: 5// array2: [-2, -1, 0, 1, 2]
console.log(array2.unshift([-4, -3]));        // expected output: 6// array2: [[-4, -3], -2, -1, 0, 1, 2]
console.log(array2.unshift([-7, -6], [-5]));  // expected output: 8// array2 is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

30. values() 

This method returns a new array iterator object that contains the values for each index in the array; it prints all the elements of the array.

  • Syntax – arr.values()
  • Parameters – This method does not accept any parameters.
  • Return value  – A new array iterator object.

Examples:

  1. Iteration using for … of loop

const array1 = ['a', 'b', 'c', 'd', 'e'];const iterator = array1.values();
for (let letter of iterator) {  console.log(letter);}  //"a" "b" "c" "d" "e"

  1. Iteration using .next()

const array2 = ['a', 'b', 'c', 'd', 'e'];const iterator = array2.values();
console.log(iterator.next());// Object { value: "a", done: false }console.log(iterator.next().value);       // "b"console.log(iterator.next()["value"]);    // "c"console.log(iterator.next());// Object { value: "d", done: false }console.log(iterator.next());// Object { value: "e", done: false }console.log(iterator.next());// Object { value: undefined, done: true }console.log(iterator.next().value);    // undefined

Conclusion 

We have covered 30 array methods in depth. I hope you’ve found this article insightful and that it helps you understand JavaScript arrays methods more clearly. Thanks for reading!  

Recent Snippet

How to use reduce over an array of objects

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.

How to get the highest or the lowest value in an array

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.