1

I'm trying to create an instance of the elements that have been added using the splice() function.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
var removed = myFish.splice(2,1, "spongebob"); 
console.log(removed); // 

The output I'm looking for is spongebob but instead I get starfish.

Any thoughts?

4
  • 1
    Are you trying to replace starfish with spongebob because if so, you did that successfully. removed is showing the element that you spliced out of the array. If you actually console.log(myFish), you will see that your array now includes spongebob. Commented Jun 30, 2020 at 15:20
  • Array.splice() will return the removed element. Commented Jun 30, 2020 at 15:24
  • It's called removed for a reason. Commented Jun 30, 2020 at 15:26
  • Why use splice in the first place if you don't want the removed item? Simply do: var added = myFish[2] = "spongebob"; Commented Jun 30, 2020 at 15:26

2 Answers 2

2

Array.splice returns the deleted elements, not the mutated array.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
console.log("Array before we splice: ", myFish);
var removed = myFish.splice(2,1, "spongebob");
console.log("Array after we splice: ", myFish);
console.log("Replaced Element ", removed, "with: ", myFish[2]);

Sign up to request clarification or add additional context in comments.

Comments

0

You are splicing by index 2 (starfish), remove 1 element and replace with 'spongebob'. starfish is removed and stored in removed var.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
var removed = myFish.splice(2, 1, "spongebob");
console.log(myFish);  //["angels", "clowns", "spongebob", "sharks"]
console.log(myFish[2]); // spongebob
console.log(removed); // ["starfish"]

1 Comment

thanks man! haha sometimes i appear to overcomplicate things :)

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.