How to remove first and last element array in JavaScript?

10-May-2023

.

Admin

How to remove first and last element array in JavaScript?

This tutorial will provide example of how to remove first and last element array in javascript. This tutorial will give you simple example of to remove first and last element in array. you will learn Remove First. if you want to see example of Last Element From Array Javascript then you are a right place. Let's get started with Remove First.

There are a few ways to remove the first and last element of an array in JavaScript:

Example 1: Using the splice() method


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to remove first and last element array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

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

arr.splice(0, 1); // Removes the first element

arr.splice(-1, 1); // Removes the last element

console.log(arr); // Output: [2, 3, 4]

</script>

</html>

Example 2: Using the shift() and pop() methods

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to remove first and last element array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

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

arr.shift(); // Removes the first element

arr.pop(); // Removes the last element

console.log(arr); // Output: [2, 3, 4]

</script>

</html>

Example 3: Using slice() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to remove first and last element array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

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

let removedFirstLastArr = arr.slice(1,-1);

console.log(removedFirstLastArr) //[2 ,3 ,4]

</script>

</html>

#JavaScript