chris_techno25
chris_techno25

Reputation: 2477

Overwrite Array Values in Javascript

Consider the array variable below...

var fruits = [];
fruits.push("banana");
fruits.push("apple");
fruits.push("mango");
fruits.push("orange");
fruits.push("grapes");

We should have these values...

fruits[0]=>"banana"
fruits[1]=>"apple"
fruits[2]=>"mango"
fruits[3]=>"orange"
fruits[4]=>"grapes"

Say I have a pointer and it's currently at number 2, so the current value is mango, how do I overwrite orange and grapes when I do another push? Is it possible? Say I wanted to add coconut but I don't want it assigned to fruits[5], what I would like to have is orange getting replaced with coconut and it goes on and on... How do I achieve this? Thank you.

Upvotes: 0

Views: 2124

Answers (4)

Carsten Massmann
Carsten Massmann

Reputation: 28196

You could even define your own "psh()" function to start inserting at an arbitrary position like this:

fruits=["banana","apple","mango","orange","grapes"];
function defpsh(arr,i){arr.psh=function(v){ this[i++]=v }}

defpsh(fruits,2); // start "pshing"at offset 2

fruits.psh('coconut');
fruits.psh('lemon');

console.log(fruits);

Upvotes: 1

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

There's already a good answer of using splice, I do not mean to disrespect it. However, splice is a method that mutates an existing array. Personally I'd prefer of using slice instead:

const newFruits = fruits.slice(0, end).concat(values);

Where end stands for the "pointer" mentioned in the question. And values represent an array of values to be added (like ['coconut']).

Upvotes: 1

Jacob
Jacob

Reputation: 78850

Use assignment to replace an item at one index:

fruits[3] = 'coconut';

...or if you don't know where it is:

fruits[fruits.indexOf('orange')] = 'coconut';

Alternatively, if you want to do a replacement with a predicate:

fruits = fruits.map(f => f === 'orange' ? 'coconut' : f);

...or use splice like @inorganik recommended if you want to do more advanced things like replacing a range of indexes with 0 or more replacements.

Lots of options. MDN is a great resource if you have a data type and want to see all the operations available. Here's some Array documentation

Upvotes: 2

inorganik
inorganik

Reputation: 25525

Use splice:

fruits.splice(3, 1, 'coconut')

The arguments are:

  1. start at index
  2. delete count
  3. replace with (optional)

Upvotes: 3

Related Questions