Tutorial
Array Methods

Arrays Methods

🎉

Read This on Github

This article is available on Github. You can read it there and contribute to it.
Github Link
Any Issue ?

⭐ Most Important Array's Methods

Example with Explanation

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.

▶️ toString()

Converts an array to a string of (comma separated) array values.

👀

The toString() method is mostly used for debugging (printing to the console) rather than converting an array to a string. If you want to convert an array to a string, use the join() method.

index.js
 
let fruits = ["apple", "banana", "cherry"];
let result = fruits.toString();
console.log(result); //Output: apple,banana,cherry
console.log(typeof result) // Output: String
 

▶️ join()

Converts all elements of an array into a string using a separator string.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
// let result = fruits.join('_'); //you can also do like this output: apple_banana_cherry
let result = fruits.join();
console.log(result); //Output: apple,banana,cherry
console.log(typeof result); // Output: String
 

▶️ pop()

Removes the last element from an array and returns that element.

👀

The pop() method changes the original array. If you want to remove an element from an array without changing the original array, use the slice() or concat() methods instead.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.pop();
console.log(result); //Output: cherry
console.log(fruits); // Output: ["apple", "banana"]
 

▶️ push()

Adds new items to the end of an array, and returns the new length.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.push('orange');
console.log(result); //Output: 4
console.log(fruits); // Output: ["apple", "banana", "cherry", "orange"]

▶️ shift()

Removes the first element from an array and returns that element.

👀

The shift() method changes the original array. If you want to remove an element from an array without changing the original array, use the slice() or concat() methods instead.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.shift();
console.log(result); //Output: apple
console.log(fruits); // Output: ["banana", "cherry"]

▶️ unshift()

Adds new items to the beginning of an array, and returns the new length. pnpm

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.unshift('orange');
console.log(result); //Output: 4
console.log(fruits); // Output: ["orange", "apple", "banana", "cherry"]

▶️ delete()

Deletes an element from an array.

👀

It won't change the original array's length. It will change the value of the element to undefined.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
delete fruits[0];
console.log(fruits); // Output: [empty, "banana", "cherry"]
console.log(fruits.length); //Output: 3

▶️ concat()

Creates a new array by merging (concatenating) existing arrays.

👀

The concat() method does not change the existing arrays. It always returns a new array.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.concat('orange');
console.log(result); //Output: ["apple", "banana", "cherry", "orange"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ sort()

Sorts the elements of an array.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.sort();
console.log(result); //Output: ["apple", "banana", "cherry"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]
👀

The sort() method sorts the elements of an array as strings. This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". Because of this, the sort() method will produce incorrect result when sorting numbers. Also it will change the original array.

index.js
let numbers = [551, 22 , 3 ,14,5,6,7,8,229,10];
let result = numbers.sort();
console.log(result); //Output: [10, 14, 229, 22, 3, 5, 551, 6, 7, 8]
console.log(numbers); // Output: [10, 14, 229, 22, 3, 5, 551, 6, 7, 8]
👀

To fix this problem, you can provide a compare function:

index.js
/*
let numbers = [551, 22 , 3 ,14,5,6,7,8,229,10];
let result = numbers.sort(function(a, b){return a - b});
console.log(result); //Output: [3, 5, 6, 7, 8, 10, 14, 22, 229, 551]
console.log(numbers); // Output: [3, 5, 6, 7, 8, 10, 14, 22, 229, 551]
*/
let numbers = [551, 22, 3, 14, 5, 6, 7, 8, 229, 10];
let compare = (a, b) => {
  return a - b; // if you do  b - a , It will give you descending order
};
 
let result = numbers.sort(compare);
console.log(result); //Output: [3, 5, 6, 7, 8, 10, 14, 22, 229, 551]
console.log(numbers); // Output: [3, 5, 6, 7, 8, 10, 14, 22, 229, 551]

In this case, the compare function returns the difference of a and b, which determines the order of the elements in the sorted array. If a is smaller than b, a - b will be negative, so a will come before b in the sorted array. If a is greater than b, a - b will be positive, so b will come before a in the sorted array. If a is equal to b, a - b will be zero, so the order of the elements will not change.

Let's consider the following numbers: [22, 14, 5].

  • When comparing 22 and 14, the compare function returns 22 - 14 = 8, which is a positive number. This means that 14 should come before 22 in the sorted array.
  • When comparing 14 and 5, the compare function returns 14 - 5 = 9, which is a positive number. This means that 5 should come before 14 in the sorted array.
  • When comparing 5 and 22, the compare function returns 5 - 22 = -17, which is a negative number. This means that 22 should come before 5 in the sorted array.

After these comparisons, the sorted array is [5, 14, 22].

▶️ splice()

Adds/Removes items to/from an array, and returns the removed item(s).

example

Change the image size by using the click-and-scroll function.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.splice(1, 0, 'orange');
console.log(result); //Output: []
console.log(fruits); // Output: ["apple", "orange", "banana", "cherry"]
👀

The splice() method changes the original array and return type is object.

index.js
let numbers = [1, 2, 3, 4, 5];
 
// Removes elements 2 and 3 (index 1 and 2) and replaces them with 6 and 7
numbers.splice(1, 2, 6, 7);
 
console.log(numbers);
// Output: [1, 6, 7, 4, 5]

In the example above, splice() was called on the numbers array with the following arguments:

  • 1: The index at which to start changing the array
  • 2: The number of elements to remove
  • 6 and 7: The elements to add to the array in place of the removed elements

So, the splice() method removed elements at index 1 and 2 (2 and 3) and added elements 6 and 7 in their place, resulting in the updated array [1, 6, 7, 4, 5].

Another good example

index.js
// Example 1
 
let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
// 1 means the starting index where the new elements will be inserted
// 9 means the number of elements to be removed from the starting index 1
let removedValue = num.splice(1, 9, 2564, 12586, 2485, 23645, 8789);
console.log(num);
/* Output :
0: 0
1: 2564
2: 12586
3: 2485
4: 23645
5: 8789
6: 10
7: 11
8: 12
9: 13
10: 14
11: 15
*/
console.log(removedValue);
/* Output :
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: 7
7: 8
8: 9
*/
console.log(typeof removedValue); //object
 
 
 
 
// _________________________________________________________
// _________________________________________________________
// ___________________Another_______________________________
// _________________________________________________________
// _________________________________________________________
 
 
 
// Example 2
 
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// 0 means the starting index where the new elements will be inserted
// 8 means the number of elements to be removed from the starting index 0
let removedValues = nums.splice(0, 8, 2525, 2676, 2548, 2568);
console.log(nums);
/* Output :
0: 2525
1: 2676
2: 2548
3: 2568
4: 9
*/
console.log(removedValues);
/* Output :
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: 7
7: 8
*/
console.log(typeof removedValues); //object
 

▶️ slice()

Slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

👀

The slice() method does not change the original array and return type is object.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.slice(1, 2);
console.log(result); //Output: ["banana"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ reverse()

Reverses the order of the elements in an array.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.reverse();
console.log(result); //Output: ["cherry", "banana", "apple"]
console.log(fruits); // Output: ["cherry", "banana", "apple"]

▶️ forEach()

👀

Instead of using a for loop, you can use the forEach() method.

index.js
let number = [25, 26, 28, 19, 89, 46];
 
for (let i=0 ; i<number.length ; i++){
  console.log(i)
}

Calls a function for each array element.

index.js
/*
let fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function (item, index, array) {
    console.log(item, index);
});
// Output: apple 0
// Output: banana 1
// Output: cherry 2
*/
 
let fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((element) => {
  console.log(element);
});
 
fruits.forEach((item) => {
  console.log(item);
});
 
fruits.forEach((array) => {
  console.log(array);
});
 
fruits.forEach((array) => {
  console.log(array);
});
 
fruits.forEach((index, item) => {
  console.log(index, item);
});
 

▶️ Array from()

Used to create an array from an object.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = Array.from(fruits);
console.log(result); //Output: ["apple", "banana", "cherry"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ map()

Creates a new array with the result of calling a function for each array element.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.map(function (item, index, array) {
    return item.toUpperCase();
});
console.log(result); //Output: ["APPLE", "BANANA", "CHERRY"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ filter()

Creates a new array with every element in an array that pass a test.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.filter(function (item, index, array) {
    return item.length > 5;
});
console.log(result); //Output: ["banana", "cherry"]
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ reduce()

Runs a function on each array element to produce (reduce it to) a single value.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
let result = fruits.reduce(function (total, item, index, array) {
    return total + item;
});
console.log(result); //Output: applebananacherry
console.log(fruits); // Output: ["apple", "banana", "cherry"]

▶️ for of

Used to get the value from an array.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
for (let item of fruits) {
    console.log(item);
}
// Output: apple
// Output: banana
// Output: cherry

▶️ for in

Used to get the keys from an array.

index.js
 
let fruits = ['apple', 'banana', 'cherry'];
for (let item in fruits) {
    console.log(item);
}
 
// Output: 0
// Output: 1
// Output: 2

⭐ Array's Methods List

Example with Explanation

NoMethodPurposeExample
1map( )Transforms each element of an array using a function[1,2,3].map(x => x * 2) returns [2,4,6]
2filter( )Filters elements of an array using a function[1,2,3].filter(x => x > 1) returns [2,3]
3sort( )Sorts elements of an array[3,1,2].sort() returns [1,2,3]
4forEach( )Calls a function for each element of an array[1,2,3].forEach(console.log) logs 1, then 2, then 3
5concat( )Concatenates two or more arrays[1,2].concat([3,4]) returns [1,2,3,4]
6every( )Tests if all elements of an array pass a test[1,2,3].every(x => x > 0) returns true
7some( )Tests if some elements of an array pass a test[1,2,3].some(x => x > 2) returns true
8includes( )Tests if an array includes a value[1,2,3].includes(2) returns true
9join( )Joins elements of an array into a string[1,2,3].join() returns "1,2,3"
10reduce( )Reduces the elements of an array to a single value by applying a function[1,2,3,4].reduce((acc, cur) => acc + cur) returns 10
11find( )Returns the first value that passes a test[1,2,3].find(x => x > 1) returns 2
12findIndex( )Returns the index of the first value that passes a test[1,2,3].findIndex(x => x > 1) returns 1
13indexOf( )Returns the index of the first occurrence of a value[1,2,3].indexOf(2) returns 1
14fill( )Fills elements of an array with a value[1,2,3].fill(0) returns [0,0,0]
15slice( )Extracts elements of an array into a new array[1,2,3].slice(1,2) returns [2]
16reverse( )Reverses the order of elements of an array[1,2,3].reverse() returns [3,2,1]
17push( )Adds one or more elements to the end of an array[1,2,3].push(4) returns [1,2,3,4]
18pop( )Removes the last element of an array[1,2,3].pop() returns 3
19shift( )Removes the first element of an array[1,2,3].shift() returns 1
20unshift( )Adds one or more elements to the beginning of an array[1,2,3].unshift(0) returns [0,1,2,3]
21splice()Adds or removes elements of an array[1,2,3].splice(1, 0, 4) returns [1,4,2,3]
22copyWithin()Copies elements within an array to a different position[1,2,3,4].copyWithin(0, 2) returns [3,4,3,4]
23entries()Returns an iterator of key-value pairs for each element in the array[1,2,3].entries() returns an iterator of [[0,1],[1,2],[2,3]]
24keys()Returns an iterator of the keys for each element in the array[1,2,3].keys() returns an iterator of [0,1,2]
25values()Returns an iterator of the values for each element in the array[1,2,3].values() returns an iterator of [1,2,3]
26flat()Flattens an array to a specified depth[[1,2],[3,4]].flat() returns [1,2,3,4]
27flatMap()Maps elements of an array to a new array and then flattens it[1,2,3].flatMap(x => [x * 2]) returns [2,4,6]
28toString()Returns a string representation of an array[1,2,3].toString() returns "1,2,3"
29toLocaleString()Returns a localized string representation of an array[1,2,3].toLocaleString() returns "1,2,3" (may vary based on locale)
30toSource()Returns a string representation of the source code of an array[1,2,3].toSource() returns "([1, 2, 3])"
31reduceRight( )Reduces elements of an array to a single value by applying a function from right to left[1,2,3,4].reduceRight((acc, cur) => acc + cur) returns 10
32Object.entries( )Returns an array of key-value pairs for an objectObject.entries({a: 1, b: 2}) returns [['a', 1], ['b', 2]]
33Object.keys( )Returns an array of the keys for an objectObject.keys({a: 1, b: 2}) returns ['a', 'b']
34Object.values( )Returns an array of the values for an objectObject.values({a: 1, b: 2}) returns [1, 2]
35Array.isArray( )Determines if a value is an arrayArray.isArray([1,2,3]) returns true
36Array.of( )Creates a new array with a given length and valuesArray.of(1, 2, 3) returns [1, 2, 3]
37Array.from( )Creates a new array from an array-like or iterable objectArray.from('abc') returns ['a', 'b', 'c']