Given an array, the task is to replace an item in a JavaScript array. There are multiple ways to replace an item in an array in JavaScript.
1. Using Array splice() Method
The splice()
method is used to remove, replace, or insert elements into an array at a specified index.
let arr = [10, 20, 30, 40, 50]; // Replace the item at index 2 arr.splice(2, 1, 100); console.log(arr); // Output: [10, 20, 100, 40, 50 ]
2. Using Array map() Method
The map()
method creates a new array by transforming each element of the original array.
let arr = [10, 20, 30, 40, 50]; let newArr = arr.map(item => item === 30 ? 100 : item); console.log(newArr); // Output: [ 10, 20, 100, 40, 50 ]
3. Using Array findIndex() Method
The findIndex()
method returns the index of the first element that satisfies a given condition, making it ideal for replacing a specific item based on a condition.
let arr = [10, 20, 30, 40, 50]; // Find the index of the value 3 let index = arr.findIndex(item => item === 30); if (index !== -1) { arr[index] = 100; } console.log(arr); // Output: [ 10, 20, 100, 40, 50 ]
4. Using a for Loop
A for
loop provides complete control over the iteration and replacement logic.
let arr = [10, 20, 30, 40, 50]; for (let i = 0; i < arr.length; i++) { if (arr[i] === 30) { arr[i] = 100; break; // Stop after the first replacement } } console.log(arr); // Output: [ 10, 20, 100, 40, 50 ]
5. Using Array forEach() Method
The forEach()
method iterates over an array, allowing you to replace items directly.
let arr = [10, 20, 30, 40, 50]; arr.forEach((item, index) => { if (item === 30) { arr[index] = 100; } }); console.log(arr); // Output: [ 10, 20, 100, 40, 50 ]
6. Replacing Multiple Items
Sometimes, you need to replace multiple items based on a condition. This can be achieved using map()
or forEach()
.
Example with map()
Method
let arr = [10, 20, 30, 40, 50]; // Replace all values greater than 3 with 99 let newArr = arr.map(item => item > 30 ? 100 : item); console.log(newArr); // Output: [ 10, 20, 30, 100, 100 ]
Example with forEach()
Method
let arr = [10, 20, 30, 40, 50]; arr.forEach((item, index) => { if (item > 30) { arr[index] = 100; } }); console.log(arr); // Output: [ 10, 20, 30, 100, 100 ]
7. Using Lodash for Simplified Operations
If you’re using Lodash, its utility functions like _.map()
or _.findIndex()
simplify array operations.
const _ = require('lodash'); let arr = [10, 20, 30, 40, 50]; // Replace the value 30 with 100 let newArr = _.map(arr, item => item === 30 ? 100 : item); console.log(newArr); // Output: [10, 20, 100, 40, 50]