1

If I have this array ['Jan', 'March', 'April', 'June']. How to replace 'April' with 'newVal' and keep all other elements unchanged. I tried

const months = ['Jan', 'March', 'April', 'June'];
months.splice(3, 1, 'newVal');
console.log(months);

I want it to return ['Jan', 'March', 'newVal', 'June'] but it returns ["Jan", "March", "April", "newVal"]

CC BY-SA 4.0
3

6 Answers 6

3

Why not assign directly?

const
    months = ['Jan', 'March', 'April', 'June'];

months[2] = 'newVal';

console.log(months);

CC BY-SA 4.0
2

You can do this:

a.splice(2,1,"newVal")

It deletes 1 element at position 2 and adds the new value "newVal"

CC BY-SA 4.0
2

You could first find the Arrray.prototype.indexOf() some "string", than you can directly replace it:

const arr = ["a", "b", "c", "d"];
const idx = arr.indexOf("c");       // 0..N or -1 if not found

// Make sure the index is found, than replace it
if (idx > -1) arr.splice(idx, 1, "newVal");

A nifty reusable function:

const replaceInArray = (arr, oldVal, newVal) => {
  const idx = arr.indexOf(oldVal);
  if (idx > -1) arr.splice(idx, 1, newVal);
};



const months = ['Jan', 'March', 'April', 'June'];
replaceInArray(months, "April", "newVal");
console.log(months)

CC BY-SA 4.0
1

If you know the value you want to replace (ie: you always want to replace 'April') :

months[months.indexOf("April")] = 'newVal';
CC BY-SA 4.0
1

Always remember that the first index of an array is always 0, so just do this instead :

months.splice(2,1,"newVal")
CC BY-SA 4.0
1

The function which you used was correct but You mistook the index value of element april of the array months

The correct index value of april is 2

So your code will be like this

const months = ['Jan', 'March', 'April', 'June'];
months.splice(2, 1, 'newVal');
console.log(months);

CC BY-SA 4.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.