Replace The First Element Of An Array In JavaScript

To replace the first element of an array in JavaScript, you can use any of these methods –

  1. Use the array index to access the first element and assign it a new value.
  2. Use the splice() method to replace the first element of an array.
  3. Use the slice() method along with the spread operator to replace the first element of the array.

Let’s discuss these methods in detail below.

replace the first element of an array in JavaScript

Method 1: Use The Array Index To Access The First Element And Assign It A New Value

In this method, we will use the array index to access the first element and then change its value.

var arr = ['one', 'two', 'three', 'four'];

arr[0] = "newFirst";

console.log(arr); //["newFirst", "two", "three", "four"]

You can also use the map() method to access the first element of the array and replace it with a new value –

var arr = ['one', 'two', 'three', 'four'];

arr = arr.map(function (element, index) {

if (index === 0) {

  return "newFirst";

} else {

  return element;

}

});

console.log(arr); // ["newFirst", "two", "three", "four"]

In the above code, we have first declared an array named arr. Then we have used the map() method to iterate over each element of the array and check if it is the first element. If it is, then we replace it with a new value “newFirst” and return it. Otherwise, we just return the original value.

Method 2: splice() To Replace The First Element Of An Array In JavaScript

In this method, we will use the splice() method to remove the first element from the array and then spread the remaining elements using the … (spread) operator.

var arr = ['one', 'two', 'three', 'four'];

var newFirst = "newFirst";

arr.splice(0, 1, newFirst);

console.log(arr); // ["newFirst", "two", "three", "four"]

In the above code, we have first declared an array named arr. Then we have used the splice() method to remove the first element from the array and add the new value at the same index.

Method 3: slice() Along With The Spread Operator To Replace The First Element Of An Array

In this method, we will use the slice() method to get all elements from the array except for the first one and then spread them using the … (spread) operator.

var arr = ['one', 'two', 'three', 'four'];

var newFirst = "newFirst";

arr = ["newFirst", ...arr.slice(1)];

console.log(arr); // ["newFirst", "two", "three", "four"]

In the above code, we have first declared an array named arr. Then we have used the slice() method to get all elements from the array except for the first one and spread them using the … (spread) operator.

Then we have added the new value “newFirst” at the beginning of the array.

So these were some of the methods that you can use to replace the first element of an array in JavaScript. Try them out and see which one suits your needs best.

If you have any questions, feel free to post them in the comments section below.

Leave a Reply