Reputation: 936
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"]
Upvotes: 1
Views: 849
Reputation: 1169
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);
Upvotes: 1
Reputation: 206111
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)
Upvotes: 2
Reputation: 46
Always remember that the first index of an array is always 0, so just do this instead :
months.splice(2,1,"newVal")
Upvotes: 1
Reputation: 136
If you know the value you want to replace (ie: you always want to replace 'April') :
months[months.indexOf("April")] = 'newVal';
Upvotes: 1
Reputation: 386578
Why not assign directly?
const
months = ['Jan', 'March', 'April', 'June'];
months[2] = 'newVal';
console.log(months);
Upvotes: 3
Reputation: 2263
You can do this:
a.splice(2,1,"newVal")
It deletes 1 element at position 2 and adds the new value "newVal"
Upvotes: 2