DEV Community

Cover image for Array Methods in JS
Vigneshwaran V
Vigneshwaran V

Posted on

Array Methods in JS

To help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.

1. JavaScript Array length

The length property of an array returns the number of elements in the array. It automatically updates as elements are added or removed.

let a = ["HTML", "CSS", "JS", "React"];
console.log(a.length);
Enter fullscreen mode Exit fullscreen mode
  • The code defines an array 'a' containing the elements "HTML", "CSS", "JS", and "React".

  • a.length returns the number of elements in the array.

  • The length property returns the length (size) of an array.


2. JavaScript Array toString() Method

The toString() method converts the given value into the string with each element separated by commas.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

let myList = fruits.toString();

console.log(myList)
Enter fullscreen mode Exit fullscreen mode

Output

Banana,Orange,Apple,Mango
Enter fullscreen mode Exit fullscreen mode
  • Every JavaScript object has a toString() method.

  • The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.


3. JavaScript Array at()

ES2022 introduced the array method at():

Example
Get the third element of fruits using at():

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(2);
console.log(fruit);
Enter fullscreen mode Exit fullscreen mode

Output

Apple
Enter fullscreen mode Exit fullscreen mode

Get the third element of fruits using []:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];
Enter fullscreen mode Exit fullscreen mode

Output

Apple
Enter fullscreen mode Exit fullscreen mode
  • The at() method returns an indexed element from an array.

  • The at() method returns the same as [].

  • at() is an ECMAScript 2022 feature.

  • Many languages allow negative bracket indexing like [-1] to access elements from the end of an object / array / string.

  • This is not possible in JavaScript, because [] is used for accessing both arrays and objects. obj[-1] refers to the value of key -1, not to the last property of the object.

  • The at() method was introduced in ES2022 to solve this problem.


4. JavaScript Array join() Method

This join() method creates and returns a new string by concatenating all elements of an array. It uses a specified separator between each element in the resulting string.

  • It behaves just like toString(), but in addition you can specify the separator.
let a = ["HTML", "CSS", "JS", "React"];
console.log(a.join('|'));
Enter fullscreen mode Exit fullscreen mode

Output

HTML|CSS|JS|React
Enter fullscreen mode Exit fullscreen mode

The join('|') method combines the array elements into a single string, with each element separated by a pipe (|) character.


5. Popping and Pushing

  • When you work with arrays, it is easy to remove elements and add new elements.

  • This is what popping and pushing is:
    Popping items out of an array, or pushing items into an array.

JavaScript Array.pop() Method
The pop() method removes the last element from an array:

let a = [20, 30, 40, 50];
a.pop();
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

[20,30,40]
Enter fullscreen mode Exit fullscreen mode

The pop() method returns the value that was "popped out".

JavaScript Array.push() Method
The push() method is used to add an element at the end of an Array. As arrays in JavaScript are mutable objects, we can easily add or remove elements from the Array.

let a = [10, 20, 30, 40, 50];
a.push(60);
a.push(70, 80, 90);
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

[10,20,30,40,50,60,70,80,90]
Enter fullscreen mode Exit fullscreen mode

The push() method returns the new array length.


6. Shifting Elements

Shifting is equivalent to popping, but working on the first element instead of the last.

** JavaScript Array.shift() Method**
The shift() method removes the first array element and "shifts" all other elements to a lower index.

let a = [20, 30, 40, 50];
a.shift();
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

[30,40,50]
Enter fullscreen mode Exit fullscreen mode

The shift() method returns the value that was "shifted out".
** JavaScript Array.unshift() Method**
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

let a = [20, 30, 40];
a.unshift(10, 20);
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

[10,20,20,30,40]
Enter fullscreen mode Exit fullscreen mode

The unshift() method returns the new array length


7. Array.isArray()

ECMAScript 5 (JavaScript 2009) added the new method Array.isArray() to JavaScript:
This method is used to check wheather the data is in Array Format or Not.

const fruits = ["Banana", "Orange", "Apple"];
console.log(Array.isArray(fruits));
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

8. JavaScript Array delete()

  • Using delete() leaves undefined holes in the array.

  • Use pop() or shift() instead.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

[ <1 empty item>, 'Orange', 'Apple', 'Mango']
Enter fullscreen mode Exit fullscreen mode

9. Merging Arrays (Concatenating)

  • In programming languages, concatenation means joining strings end-to-end.

  • Concatenation "snow" and "ball" gives "snowball".

  • Concatenating arrays means joining arrays end-to-end.

JavaScript Array concat() Method
The concat() method is used to concatenate two or more arrays and it gives the merged array.

let a1 = [11, 12, 13];
let a2 = [14, 15, 16];
let a3 = [17, 18, 19];

let newArr = a1.concat(a2, a3);
console.log(newArr);
Enter fullscreen mode Exit fullscreen mode

Output

[11,12,13,14,15,16,17,18,19]

Enter fullscreen mode Exit fullscreen mode

The concat() method does not change the existing arrays. It always returns a new array.
The concat() method can take any number of array arguments.
The concat() method can also take strings as arguments:

const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter"); 
console.log(myChildren)
Enter fullscreen mode Exit fullscreen mode

Output

[ 'Emil', 'Tobias', 'Linus','Peter' ]
Enter fullscreen mode Exit fullscreen mode

10. Array copyWithin()

The copyWithin() method copies array elements to another position in an array:

Examples
Copy to index 2, all elements from index 0:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

['Banana','Orange','Banana','Orange']
Enter fullscreen mode Exit fullscreen mode

Copy to index 2, the elements from index 0 to 2:

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.copyWithin(2, 0, 2);

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

['Banana','Orange','Banana','Orange','Kiwi']
Enter fullscreen mode Exit fullscreen mode

The copyWithin() method overwrites the existing values.
The copyWithin() method does not add items to the array.
The copyWithin() method does not change the length of the array.


11. Flattening an Array

  • Flattening an array is the process of reducing the dimensionality of an array.

  • Flattening is useful when you want to convert a multi-dimensional array into a one-dimensional array.

JavaScript Array flat()

  • ES2019 Introduced the Array flat() method.

  • The flat() method creates a new array with sub-array elements concatenated to a specified depth.

const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();

console.log(myArr)     // it doesn't modify the original Array
console.log(newArr)   // it return new Array as output
Enter fullscreen mode Exit fullscreen mode

Output

[[1,2],[3,4],[5,6]]
[1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode
  • flat() is an ECMAScript 2019 feature.

12. JavaScript Array flatMap()

  • ES2019 added the Array flatMap() method to JavaScript.

  • The flatMap() method first maps all elements of an array and then creates a new array by flattening the array.

  • flatMap() is a combination of:

  • map() → transforms each element.

  • flat() → flattens one level of nested arrays

const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);

console.log(myArr)
console.log(newArr)
Enter fullscreen mode Exit fullscreen mode

Output

[1, 2, 3, 4, 5, 6]
[ 
  1,10,2,20,3,
  30,4,40,5,50,
  6,60
]
Enter fullscreen mode Exit fullscreen mode

Difference Between map() and flatMap()

Using map()

const arr = [1, 2, 3];

const result = arr.map(x => [x, x * 2]);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

[
  [1, 2],
  [2, 4],
  [3, 6]
]
Enter fullscreen mode Exit fullscreen mode

Using flatMap()

const arr = [1, 2, 3];

const result = arr.flatMap(x => [x, x * 2]);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

flatMap() executes a callback function on each array element and then combines (flattens) the returned arrays into a single array by removing one level of nesting.


13. Splicing and Slicing Arrays

  • The splice() method adds new items to an array.

  • The slice() method slices out a piece of an array.

JavaScript Array splice()

splice() is used to add, remove, or replace elements in an array.

  • It modifies the original array.

Syntax

array.splice(start, deleteCount, item1, item2, ...)
Enter fullscreen mode Exit fullscreen mode

1. Remove Elements

const fruits = ["Apple", "Banana", "Mango", "Orange"];

fruits.splice(1, 2);

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Orange"]
Enter fullscreen mode Exit fullscreen mode

What happened?

Index:   0        1         2        3
Array: ["Apple","Banana","Mango","Orange"]
Enter fullscreen mode Exit fullscreen mode

Start at index 1 ("Banana")
Delete 2 elements:

"Banana", "Mango"
Enter fullscreen mode Exit fullscreen mode

Remaining:

["Apple", "Orange"]
Enter fullscreen mode Exit fullscreen mode

2. Add Elements

const fruits = ["Apple", "Mango"];

fruits.splice(1, 0, "Banana");

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

What happened?

  • Start at index 1

  • Delete 0 elements

  • Insert "Banana"

3. Replace Elements

const fruits = ["Apple", "Banana", "Mango"];

fruits.splice(1, 1, "Orange");

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Orange", "Mango"]
Enter fullscreen mode Exit fullscreen mode

What happened?

  • Start at index 1

  • Remove 1 element ("Banana")

  • Insert "Orange"

4. Add Multiple Elements

const fruits = ["Apple", "Mango"];

fruits.splice(1, 0, "Banana", "Orange");

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Banana", "Orange", "Mango"]
Enter fullscreen mode Exit fullscreen mode

5. Return Value of splice()

splice() returns the removed elements.

const fruits = ["Apple", "Banana", "Mango"];

let removed = fruits.splice(1, 1);

console.log(removed);
console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Banana"]

["Apple", "Mango"]
Enter fullscreen mode Exit fullscreen mode

6. Using Negative Index

const fruits = ["Apple", "Banana", "Mango", "Orange"];

fruits.splice(-2, 1);

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Banana", "Orange"]
Enter fullscreen mode Exit fullscreen mode

Explanation

-1 → Orange
-2 → Mango
-3 → Banana
-4 → Apple
Enter fullscreen mode Exit fullscreen mode

Start from "Mango" and delete 1 element.
So splice() is the CRUD method of arrays because it can:

  • Create (add elements)

  • Read (you can get removed elements)

  • Update (replace elements)

  • Delete (remove elements)


JavaScript Array toSpliced()

ES2023 added the Array toSpliced() method as a safe way to splice an array without altering the original array.

  • The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method altered the original array.
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);

console.log(months)
console.log(spliced)
Enter fullscreen mode Exit fullscreen mode

Output

['Jan','Feb','Mar','Apr']
['Feb','Mar','Apr']
Enter fullscreen mode Exit fullscreen mode

Here it doesn't modify the original Array so it is safe when we need our original Array in entire code.


JavaScript Array slice()

slice() is used to extract a portion of an array and create a new array.

  • It does not modify the original array.

Syntax

array.slice(start, end)
Enter fullscreen mode Exit fullscreen mode
  • start => Starting index (included)

  • end => Ending index (excluded)

Example 1: Basic Usage

const fruits = ["Apple", "Banana", "Mango", "Orange"];

let result = fruits.slice(1, 3);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output

["Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Explanation:

Indexes:

0 -> Apple
1 -> Banana
2 -> Mango
3 -> Orange
Enter fullscreen mode Exit fullscreen mode

slice(1,3) means:
Start from index 1
Stop before index 3
So it returns:

["Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Example 2: Omitting end

const fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits.slice(2));
Enter fullscreen mode Exit fullscreen mode

Output

["Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

It starts from index 2 and takes everything till the end.

Example 3: Copy an Array

const fruits = ["Apple", "Banana", "Mango"];

const copy = fruits.slice();

console.log(copy);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

This is a common way to create a shallow copy of an array.

Example 4: Negative Index

const fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits.slice(-2));
Enter fullscreen mode Exit fullscreen mode

Output

["Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

Negative indexes count from the end:

-1 -> Orange
-2 -> Mango
-3 -> Banana
-4 -> Apple
Enter fullscreen mode Exit fullscreen mode

Example 5: Original Array Remains Unchanged

const fruits = ["Apple", "Banana", "Mango"];

let result = fruits.slice(1);

console.log(result);
console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Banana", "Mango"]
["Apple", "Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Notice that fruits is unchanged.
slice() is used to extract a part of an array and return it as a new array without changing the original array.


References

https://www.w3schools.com/js/js_array_methods.asp
https://www.geeksforgeeks.org/javascript/javascript-array-methods/
https://www.programiz.com/javascript/library/array

Top comments (0)