0

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.

1
  • 2
    you are looking for .splice() Commented Jun 9, 2020 at 15:34

4 Answers 4

3

Use splice:

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

The arguments are:

  1. start at index
  2. delete count
  3. replace with (optional)
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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']).

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.