Skip to main content

How to Replace an Element in a JavaScript Array

Replacing an element in an array is a common data manipulation task. Depending on your goal, you might want to modify the original array directly (a mutation), or you might prefer to create a new array with the updated value, leaving the original unchanged (an immutable operation).

This guide will teach you the best modern methods for both approaches. You will learn how to use indexOf() and bracket notation for direct mutation and the powerful map() method for an immutable replacement.

The Core Problem: Mutating vs. Immutable Operations

Before you replace an element, you must decide on your approach:

  • Mutation (In-Place): You change the original array directly. This is efficient but can sometimes lead to unexpected behavior in complex applications if the original array is being used elsewhere.
  • Immutable: You create a brand new array with the updated value. This is often safer and leads to more predictable code, especially in frameworks like React, but it uses slightly more memory.

Method 1 (Mutation): Finding the Index and Replacing

This is the most direct and common way to replace the first occurrence of a value in an array.

The logic:

  1. Use the Array.prototype.indexOf() method to find the index of the element you want to replace.
  2. If the element is found (indexOf() does not return -1), use bracket notation to assign a new value at that index.

For example, you have an array and need to replace the element 'b' with 'z'.

// Problem: Replace 'b' with 'z' in this array.
const letters = ['a', 'b', 'c', 'b'];

Solution:

const letters = ['a', 'b', 'c', 'b'];
const valueToReplace = 'b';
const newValue = 'z';

const index = letters.indexOf(valueToReplace);

if (index !== -1) {
letters[index] = newValue;
}

console.log(letters);

Output:

['a', 'z', 'c', 'b']
note

This approach is simple and efficient. It modifies the letters array directly and stops after replacing only the first match.

Method 2 (Immutable): Creating a New Array with map()

The Array.prototype.map() method is the standard tool for creating a new array based on the contents of an existing one. This is the recommended approach for immutable operations.

The logic:

  1. Iterate over the original array using map().
  2. For each element, check if it's the one you want to replace.
  3. If it is, return the new value.
  4. If it's not, return the original element.

Solution: this example replaces the first occurrence of 'b'. A flag (replaced) is used to ensure we only replace the first match.

const letters = ['a', 'b', 'c', 'b'];
const valueToReplace = 'b';
const newValue = 'z';

let replaced = false;

const newLetters = letters.map(item => {
// Check if it's the item we want to replace and if we haven't replaced it yet
if (item === valueToReplace && !replaced) {
replaced = true;
return newValue;
}
return item;
});

console.log(newLetters); // Output: ['a', 'z', 'c', 'b']
console.log(letters); // Output: ['a', 'b', 'c', 'b'] (The original is unchanged)

Output:

['a', 'z', 'c', 'b']
['a', 'b', 'c', 'b']

Replacing All Occurrences of a Value

Both methods can be easily adapted to replace every occurrence of a value.

Method 1 (Mutation): Using a forEach() Loop

You can iterate with forEach() and modify the array by index.

const letters = ['a', 'b', 'c', 'b'];

letters.forEach((item, index) => {
if (item === 'b') {
letters[index] = 'z';
}
});

console.log(letters); // Output: ['a', 'z', 'c', 'z']

Output:

['a', 'z', 'c', 'z']

Method 2 (Immutable): Using map()

The map() method is even cleaner for this task. The logic is simpler because you don't need a flag to stop after the first replacement.

const letters = ['a', 'b', 'c', 'b'];

const newLetters = letters.map(item => {
if (item === 'b') {
return 'z';
}
return item;
});

// A more concise version using a ternary operator
// const newLetters = letters.map(item => (item === 'b' ? 'z' : item));

console.log(newLetters); // Output: ['a', 'z', 'c', 'z']

Output:

['a', 'z', 'c', 'z']
note

This is the most common and readable pattern for replacing all occurrences in an immutable way.

Conclusion

Replacing elements in a JavaScript array is a straightforward task, and the best method depends on whether you want to modify the original array.

  • To mutate the original array and replace only the first occurrence, the best method is to use indexOf() to find the element and bracket notation (arr[index] = newValue) to replace it.
  • To create a new array and leave the original unchanged, the map() method is the recommended, idiomatic solution. It is clean, readable, and highly flexible for replacing either the first or all occurrences.