DEV Community

Cover image for Replacing an Array item by Index with Refactoring Example
John Peters
John Peters

Posted on

Replacing an Array item by Index with Refactoring Example

Photo courtesy of DreamsTime

Original Code

let items = ["one","two","three"];
let newValue = "four";
let found = items.find(item=>item==="two");
let index = items.indexOf(found);
items.splice(index,1,newValue);
Enter fullscreen mode Exit fullscreen mode

First Mutable Refactor

// mutable example
function replace(items, currentValue, newValue){
  let found = items.find(item=>item===currentValue);
  let index = items.indexOf(found);
  items.splice(index,1,newValue);
}
Enter fullscreen mode Exit fullscreen mode

Second Immutable Refactor

// immutable example
function replace(items,currentValue, newValue):[]{
  let list = [...items];
  let found = list.find(item=>item===currentValue);
  let index = list.indexOf(found);
  list.splice(index,1,newValue);
  return list;
}
Enter fullscreen mode Exit fullscreen mode

What would the last refactor look like? Let us know in comments below.

JWP2020 Replacing Items in an Array

Top comments (0)