/

How to Replace an Item in an Array in JavaScript

How to Replace an Item in an Array in JavaScript

Replacing an item in an array in JavaScript is a common operation when working with arrays. This can be easily achieved using a simple assignment if you know the index of the item.

Here’s an example:

1
2
3
4
5
6
7
const items = ['a', 'b', 'c', 'd', 'e', 'f'];
const i = 2;

items[i] = '--NEW-ITEM--';

console.log(items);
//[ 'a', 'b', '--NEW-ITEM--', 'd', 'e', 'f' ]

In the code above, we have an array called items with multiple elements. The variable i represents the index of the item we want to replace. By assigning a new value to items[i], we can replace the content of that item in the array. In this case, we replaced the item at index 2 with --NEW-ITEM--.

If you don’t know the index of the item you want to replace, you can first find the index using techniques like finding the index of an item in an array in JavaScript.

By mastering the technique of replacing items in an array, you can easily manipulate array elements and modify their values according to your needs.

tags: [“JavaScript”, “array manipulation”, “replace array item”]