Important Array Methods

Important Array Methods

Before learning array methods .you have to know how arrays are created
read here

let's move to the array methods

push() Method

The push() method adds new items to the end of an array.

The push() method changes the length of the array and returns a new length

Syntax

array.push(item1, item2, ..., itemN)

Parameters

item1, item2, ..., itemN

The element(s) to add to the end of the array. A minimum one element is required

Return Value

The new length of the array.

Example

const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");
console.log(sports); // ['soccer','baseball','football','swimming']
console.log(sports.length) // 4

unshift() Method

The unshift() method adds new elements to the beginning of an array and returns the new length of the array.

Syntax

array.unshift(item1, item2, ..., itemN)

Parameters

item1, item2, ..., itemN

The element(s) to add to the front of the array. A minimum one element is required

Return Value

The new length of the array.

Example

const sports = ["soccer", "baseball"];
const total = sports.unshift("football", "swimming");
console.log(sports); // [ 'football', 'swimming', 'soccer', 'baseball' ]
console.log(sports.length) // 4

pop() Method

The pop() method removes the last element from an array and returns the removed element. This method changes the length of the array.

Syntax

array.pop()

Parameters

NO parameters

Return Value

The removed element from the array; undefined if the array is empty.

Example

const sports = ["soccer", "baseball"];
const total = sports.pop();
console.log(total) // baseball
console.log(sports); // [ 'soccer']
console.log(sports.length) // 1

shift() Method

The pop() method removes the first element from an array and returns the shifted element. This method changes the length of the array.

Syntax

array.shift()

Parameters

NO parameters

Return Value

The removed element from the array; undefined if the array is empty.

Example

const sports = ["soccer", "baseball"];
const total = sports.shift();
console.log(total) // soccer
console.log(sports); // [ 'baseball']
console.log(sports.length) // 1

slice() Method

The slice() method returns selected elements in an array, as a new array.
The slice() method selects from a given start, up to a end( not included). where start and end represent the index of items in that array.

The original array will not be modified or changed.

Syntax

array.slice()
array.slice(start)
array.slice(start, end)

Parameters

Both are optional

start : Start position. Default is 0.
Negative numbers select from the end of the array.

end : End position. Default is last element.
end position element is not included.
Negative numbers select from the end of the array.

Return Value

A new array containing the selected elements.

Example

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

splice() Method

The splice() method in JavaScript is used to change the contents of an array by removing, replacing, or adding elements. It modifies the original array and returns an array containing the removed elements (if any).

Syntax

array.splice(startIndex, deleteCount, item1, item2, ...);

Parameters

  • startIndex is the index at which the modification should start. It can be a positive or negative number. If negative, it counts from the end of the array. (Required)

  • deleteCount specifies the number of elements to remove from the array, starting from the startIndex. If set to 0, no elements are removed. (Optional)

  • item1, item2, ... are optional arguments representing the elements to be added to the array at the startIndex.(Optional)

Return Value

An array containing the deleted elements. If no elements are removed, an empty array is returned.

Example

// To Remove elements from an array:
const numbers = [1, 2, 3, 4, 5];
const result = numbers.splice(2, 2);
console.log(numbers) //  [1, 2, 5]
console.log(result )  // [3, 4]

// To Replace elements in an array:
const fruits = ['apple', 'banana', 'orange'];
const result= fruits.splice(1, 1, 'grape', 'kiwi');
console.log(numbers) //   ['apple', 'grape', 'kiwi', 'orange']
console.log(result ) // ['banana']

// Add elements to an array:
const colors = ['red', 'green', 'blue'];
const result=colors.splice(1, 0, 'yellow', 'purple');
console.log(numbers) //   ['red', 'yellow', 'purple', 'green', 'blue']
console.log(result ) // [ ]

// Remove elements and add new elements simultaneously:
const animals = ['elephant', 'lion', 'tiger', 'zebra'];
const result = animals.splice(1, 2, 'giraffe', 'monkey');
console.log(numbers) //   ['elephant', 'giraffe', 'monkey', 'zebra']
console.log(result ) // ['lion', 'tiger']

const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const result = myFish.splice(-2, 1);
console.log(numbers) //   ["angel", "clown", "sturgeon"]
console.log(result ) // ["mandarin"]

concat() Method

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Syntax

array1.concat(array2, array3, ..., arrayN)

Parameters

array2,array2...,arrayN : Arrays to concatenate into a new array.
It is required

Return Value

A new Array instance.

Example

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];
let result=numbers.concat(fruits);
console.log(result);  //  [ 1, 2, 3, 4, 5, 'apple', 'banana', 'orange' ]


const colors = ['red', 'green', 'blue'];
const animals = ['elephant', 'lion', 'tiger', 'zebra'];
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
let result= colors.concat(animals,myFish);
console.log(result);
 // [
  'red',      'green',
  'blue',     'elephant',
  'lion',     'tiger',
  'zebra',    'angel',
  'clown',    'mandarin',
  'sturgeon'
]

const arr1 = [1, 2, [3, 4]];
const arr2 = [[5, 6], 7, 8];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [ 1, 2, [ 3, 4 ], [ 5, 6 ], 7, 8 ]

reverse() Method

The reverse() method reverses the order of the elements in an array. This method changes the original array.The reverse() method returns reference to the original array, so mutating the returned array will mutate the original array as well.

Syntax

array.reverse()

Parameters

No parameters

Return Value

The array after it has been reversed.

Example

const numbers = [1, 2, 3, 4, 5];
let result = numbers.reverse();
console.log(result); // [5,4,3,2,1]
const numbers = [105, 200, 300, 44, 50];
let result = numbers.reverse();
console.log(result); // [ 50, 44, 300, 200, 105 ]

Here you can see that in reverse() method does not take into consideration of greater or smaller numbers but it just reverses the given array.

const colors = ['red', 'green', 'blue'];
let result = colors.reverse();
console.log(result); // [ 'blue', 'green', 'red' ]

It mutates the original array and does not create a new copy. The elements in the array are rearranged in-place, so the original array is modified.

In case you want reverse() to not mutate the original array, but return a shallow-copied array like other array methods .you can use map() or else you first create a shallow copy using the spread operator or slice() .


toString() Method

The toString() method returns a string with array values separated by commas.

The toString() method does not change the original array.

Syntax

array.toString()

Parameters

No parameters

Return Value

A string representing the elements of the array.

Example

const colors = ['red', 'green', 'blue'];
let result = colors.toString();
console.log(result); // red,green,blue

sort() Method

The sort() sorts the elements of an array.

The sort() modifies the original array.

The sort() sorts the elements as strings in alphabetical and ascending order In case of numbers it sorts in "25" is bigger than "100", because "2" is bigger than "1". taking into consideration of first digit number.

Syntax

array.sort(compareFunction)

Parameters

compareFunction : It is an optional. it is used to sort numbers

Return Value

The array with the items sorted.

Example

const colors = ['red', 'green', 'blue'];
let result = colors.sort();
console.log(result); // [ 'blue', 'green', 'red' ]
const point = [40, 100, 1, 5, 25, 10];
let result = point.sort();
console.log(result); // [ 1, 10, 100, 25, 40, 5 ]

Here you can see that sorted taking into consideration of first digit number

const point = [40, 100, 1, 5, 25, 10];
let result = point.sort((a, b) => b - a);
console.log(result); // [ 100, 40, 25, 10, 5, 1 ]
const point = [40, 100, 1, 5, 25, 10];
let result = point.sort((a, b) => a - b);
console.log(result); //   [ 1, 5, 10, 25, 40, 100 ]

some() Method

The some() method in JavaScript is used to check if at least one element in an array satisfies a given condition. It iterates over each element of the array and returns true if the callback function returns true for any of the elements. If no element satisfies the condition, it returns false.

Syntax

array.some(callback(element[, index[, array]])[, thisArg])

Parameters

callback is the function to test each element of the array.

It can take three arguments: element (The value of the current element.), index (optional, the index of the current element), and array (optional, the array on which some() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

true if any one of the aray elements pass the test, otherwise false

Example

const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some((number) => number % 2 === 0);
console.log(hasEvenNumber);
// Output: true

indexOf() Method

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. By default the search starts at the first element and ends at the last.The indexOf() method starts at a specified index and searches from left to right.

Syntax

indexOf(searchElement, fromIndex)

Parameters

searchElement: value to search for (Required)
fromIndex: Where to start the search. The default value to start index is 0.
Negative values start the search from the end of the array.

Return Value

The first index of the element in the array. if it is not found then -1.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", -1); 
console.log(index) // 4

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison')); // 1

console.log(beasts.indexOf('bison', 2)); // 4

console.log(beasts.indexOf('giraffe'));   // -1

lastIndexOf() Method

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.By defalt the search starts at the last element and ends at the first.The lastIndexOf() starts at a specified index and searches from right to left

Syntax

lastIndexOf(searchElement, fromIndex)

Parameters

searchElement: value to search for (Required)
fromIndex: Where to start the search. The default is the last element (array.length-1).
Default is the last element (array.length-1).

Return Value

The last index of the element in the array.if it is not found then -1.

Example

const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
console.log(fruits.lastIndexOf("Apple", -2)); // 3
console.log(fruits.lastIndexOf("Apple", 4));  // 3
console.log(fruits.lastIndexOf("Apple"));    // 5
console.log(fruits.lastIndexOf("Apple", 1)); // 1

includes() Method

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. this method is case Sensitive.

Syntax

includes(searchElement, fromIndex)

Parameters

searchElement: value to search for (Required)
fromIndex: Where to start the search. The default is the first element (0).

Return Value

true if the value is found, otherwise false

Example

const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana","Watermelon"];
console.log(fruits.includes("Apple")); // true
console.log(fruits.includes("Grapes"));  // false
console.log(fruits.includes("Apple", 4));  // false
console.log(fruits.includes("apple")); // false

every() Method

The every() method tests whether all elements in the array pass the test condition provided by the function. if it passes the test condition for all elements then it is true or else false.The every() method does not change the original array

Syntax

every(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

true if all the elements passes the condition , otherwise false

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.every((value)=> value >= 10)
console.log(result);  // true

let result1=array.every((value)=> value < 10)
console.log(result1);  // false

find() Method

The find() method returns the value of the first element that passes a condition. The find() method returns undefined if no elements are found. The find() method does not change the original array.

Syntax

find(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

The value of the first element that passes the test. Otherwise, it returns undefined.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.find((value)=> value >= 10)
console.log(result);  // 20

let result1=array.find((value)=> value >= 20)
console.log(result1);  // 20

let result2=array.find((value)=> value >= 21)
console.log(result2);  // 30

let result3=array.find((value)=> value < 10)
console.log(result3);  // undefined

Here you can see that in the first example condition was given to find a value that is greater and equal to 10. we can clearly say that 10 is the first value from all the elements that satisfy the condition. but the result gives is 20. But why? Because it iterates from the first element where element 20 satisfies the condition in the first element only.


findIndex() Method

It is similar to find() method. The findIndex() method returns the index (position) of the first element that passes a condition. The findIndex() method returns -1 if no elements are found.The findIndex() method does not change the original array.

Syntax

findIndex(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

The index of the first element that passes the condition. Otherwise, it returns -1.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.findIndex((value)=> value >= 10)
console.log(result);  // 0

let result1=array.findIndex((value)=> value >= 20)
console.log(result1);  // 0

let result2=array.findIndex((value)=> value >= 21)
console.log(result2);  // 1

let result3=array.findIndex((value)=> value < 10)
console.log(result3);  // -1

findLast() Method

It is similar to the find() method. The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function.The findLast() method returns undefined if no elements are found. The findLast() method does not change the original array.

Syntax

findLast(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

The value of the element in the array with the highest index value that satisfies the provided test function. Otherwise, it returns undefined.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.find((value)=> value >= 10)
console.log(result);  // 13

let result1=array.find((value)=> value >= 20)
console.log(result1);  // 29

let result2=array.find((value)=> value >= 21)
console.log(result2);  // 29

let result3=array.find((value)=> value < 10)
console.log(result3);  // undefined

findLastIndex() Method

It is similar to the findLast() method. The findLastIndex() method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. The findLastIndex() method returns -1 if no elements are found. The findLastIndex() method does not change the original array.

Syntax

findLastIndex(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

The index of the last element in the array with the highest index value that satisfies the provided test function. Otherwise, it returns -1.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.findLastIndex((value)=> value >= 10)
console.log(result);  // 5

let result1=array.findLastIndex((value)=> value >= 20)
console.log(result1);  // 3

let result2=array.findLastIndex((value)=> value >= 21)
console.log(result2);  // 3

let result3=array.findLastIndex((value)=> value < 10)
console.log(result3);  // -1

map() Method

map() creates a new array by calling the callback function provided as an argument on each element in the input array.map() does not change the original array.

Syntax

map(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

A new array with each element being the result of the callback function.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.map((value)=> value/10)
console.log(result);  // [ 2, 3, 3.9, 2.9, 1, 1.3 ]

let result1=array.map((value)=> value*2)
console.log(result1);  // [ 40, 60, 78, 58, 20, 26 ]

filter() Method

The filter() method creates a new array containing elements that pass a condition provided by a function.The filter() method does not change the original array.

Syntax

filter(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

A new array with arrays of elements that pass the test. Otherwise, it returns an empty array.

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.filter((value)=> value > 10)
console.log(result);  // [ 20, 30, 39, 29, 13 ]

let result1=array.filter((value)=> value > 50)
console.log(result1);  // []

reduce() Method

The reduce() method uses a reducer function on each element of the array, returning a single output value.The reduce() method does not change the original array.

Syntax

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

Parameters

callbackFn: A function to execute for each element in the array. It can take four arguments: accumulator(Required, the previously returned value of the function.On the first call, initialValue if specified, otherwise the value of array[0].), currentValue (Required, the index of the current element), index (optional, The index of the current element.) array(optioinal,The array the current element belongs to.)
initialValue(Optional):A value to be passed to the function as the initial value.

Note:- Thrown an TypeErrorif the array contains no elements and initialValue is not provided.

Return Value

The accumulated result from the last call of the callback function.

Example

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum);
// Output: 15

In this example, the reducer function (accumulator, currentValue) => accumulator + currentValue calculates the sum of all numbers in the array. The initial value of the accumulator is 0, and on each iteration, the current number is added to the accumulator. The final sum of 15 is returned as the result.


forEach() Method

The forEach() method calls a function for each element in an array.

Syntax

forEach(callbackFn, thisArg)

Parameters

callbackFn: A function to execute for each element in the array. It can take three arguments: element (The value of the current element), index (optional, the index of the current element), and array (optional, the array on which every() was called).

thisArg (optional) is the value to use as this when executing the callback function.

Return Value

undefined

Example

const array = [20, 30, 39, 29, 10, 13];
let result=array.forEach((value)=> console.log(value));
// 20
// 30
// 39
// 29
// 10
// 13

entries() Method

The entries() method returns an Array Iterator object with key/value pairs.The entries() method does not change the original array.

Syntax

array.entries()

Parameters

No parameters

Return Value

An array like iterable with key/value pairs.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const iterable = fruits.entries();

for (let x of iterable ) {
  console.log(x)
}
output:
[ 0, 'Banana' ]
[ 1, 'Orange' ]
[ 2, 'Apple' ]
[ 3, 'Mango' ]


const array = ['a', 'b', 'c'];

const iterator1 = array.entries();
console.log(iterator1.next().value);   // [ 0, 'a' ]
console.log(iterator1.next().value);    // [ 1, 'b' ]

flat() Method

The flat() method concatenates sub-array elements.

Syntax

array.flat(depth)

Parameters

depth :Optional. How deep a nested array should be flattened. Default is 1.

Return Value

The flattened array.

Example

const myArr = [[1,2],[3,4],[5,6]];
const result= myArr.flat();
console.log(result);  // [ 1, 2, 3, 4, 5, 6 ]

const myArr1 = [1, 2, [3, [4, 5, 6], 7], 8];
const result1= myArr1.flat();
console.log(result1);  //  [ 1, 2, 3, [ 4, 5, 6 ], 7, 8 ]

join() Method

The join() method returns an array as a string.The join() method does not change the original array.Any separator can be specified. The default is comma (,).

Syntax

array.join(separator)

Parameters

separator : Optional. The separator to be used.. Default is comma(,).

Return Value

he array values, separated by the specified separator.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let result= fruits.join();
let result1= fruits.join("and");
let result2= fruits.join("-");
console.log(result);  // [Banana,Orange,Apple,Mango
console.log(result1);  // Banana and Orange and Apple and Mango
console.log(result2);  // Banana - Orange - Apple - Mango

at() Method

The at() method returns an indexed element from an array.

Syntax

array.at(index)

Parameters

index : Optional. The index (position) of the array element to be returned. Default is 0. -1 returns the last element.

Return Value

The element of the given position (index) in the array.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];
console.log(fruit) //   Apple