remove first and last element from array javascript and seprated by comma

How to Remove First and Last Element from Array in JavaScript and Separate by Comma

As a web developer, I have come across various scenarios where I needed to remove the first and last element from an array in JavaScript and separate them by a comma. Here, I am going to explain how I did it.

Method 1: Using slice()

The easiest way to remove the first and last element from an array in JavaScript is by using the slice() method. The slice() method returns a new array containing the selected elements. Here is how to achieve this:


let arr = ['one', 'two', 'three', 'four', 'five'];
let newArr = arr.slice(1, -1);
let result = newArr.join();
console.log(result);

In the above code, we first create an array called arr with five elements. Then, we use the slice() method to remove the first and last element from the array. The slice() method takes two arguments: the starting and ending index of the selected elements. In our case, we want to remove the first and last element, so we pass 1 as the starting index and -1 as the ending index. Finally, we use the join() method to join the remaining elements with a comma and store it in a variable called result.

Method 2: Using splice()

Another way to remove the first and last element from an array in JavaScript is by using the splice() method. The splice() method changes the content of an array by removing or replacing existing elements and/or adding new elements. Here is how to achieve this:


let arr = ['one', 'two', 'three', 'four', 'five'];
arr.splice(0, 1);
arr.splice(arr.length - 1, 1);
let result = arr.join();
console.log(result);

In the above code, we first create an array called arr with five elements. Then, we use the splice() method to remove the first and last element from the array. The splice() method takes two arguments: the starting index and the number of elements to remove. In our case, we want to remove the first element, so we pass 0 as the starting index and 1 as the number of elements to remove. Similarly, we want to remove the last element, so we pass arr.length - 1 as the starting index (which is the last index of the array) and 1 as the number of elements to remove. Finally, we use the join() method to join the remaining elements with a comma and store it in a variable called result.

Both methods are effective in removing the first and last element from an array in JavaScript and separating them by a comma. You can choose whichever method you prefer based on your requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe