Ali Husham
Ali Husham

Reputation: 936

How to replace an element in an array without changing the other elements?

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

Answers (6)

Sandrin Joy
Sandrin Joy

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

Roko C. Buljan
Roko C. Buljan

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

Adel A
Adel A

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

VincentM
VincentM

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

Nina Scholz
Nina Scholz

Reputation: 386578

Why not assign directly?

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

months[2] = 'newVal';

console.log(months);

Upvotes: 3

pinturic
pinturic

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

Related Questions