loading...
Cover image for Replacing an Array item by Index with Refactoring Example

Replacing an Array item by Index with Refactoring Example

jwp profile image John Peters ・1 min read

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);

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);
}

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;
}

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

JWP2020 Replacing Items in an Array

Discussion

pic
Editor guide