How can you replace an item in a JavaScript array?

Hi!!

I’m working with arrays and have a quick question about manipulating their contents.

Given an array like var items = [523, 3452, 334, 31, ..., 5346];, what’s the best way to find and replace a specific value (e.g., 3452) with a new one (e.g., 1010)?

I’m looking for the most efficient or idiomatic way to achieve this within a JavaScript array.

Any insights or code examples would be super helpful! Thanks! :blush:

Hey @keerti_gautam! Your question about finding and replacing a specific value in a JavaScript array is a common task, and there’s a straightforward approach for it.

You can easily find the item’s position within the array using indexOf, and then replace it directly by its index:

JavaScriptconst idx = items.indexOf(3452);
if (idx !== -1) {
  items[idx] = 1010;
}

This method is quite simple and works effectively if you primarily want to replace only the first occurrence of the value you’re looking for.

Hope you find this useful! Thank you.

Hello there! Adding another approach to the discussion about finding and replacing values in a JavaScript array, building on the indexOf method given by @Ambikayache .

If you want to replace all instances of that specific value, the map method is a fantastic choice.

Here’s how you’d use it:

items = items.map(item => item === 3452 ? 1010 : item);

This elegant solution creates a new array with all the replacements applied, which is particularly great if the value you’re targeting might appear multiple times within your original array. It’s a clean and functional way to handle mass replacements.

Hope this helps you out @keerti_gautam!

Heyy @keerti_gautam, @Ambikayache and @emma-crepeau. I see indexOf and map methods` have already been discussed.

If you want to replace all occurrences of that value and keep the exact same array reference (meaning, changing it in place), you can simply loop through the array:

for(let i = 0; i < items.length; i++) {
  if(items[i] === 3452) {
    items[i] = 1010;
  }
}

This method directly changes the original array in place, which is incredibly handy for scenarios where you need to preserve references to the array, rather than creating a new one.

I guess this would offer you a clear solution for in-place replacements! :upside_down_face: