Basic Data Structures: Add Items Using splice()

Tell us what’s happening:
What is wrong in this code?

Your code so far


function htmlColorNames(arr) {
  // change code below this line
  let newColor = ['DarkSalmon', 'BlanchedAlmond'];
  arr.splice(0, 2, newColor);
  // change code above this line
  return arr;
} 
 
// do not change code below this line
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:

  let newColor = ['DarkSalmon', 'BlanchedAlmond'];
  arr.splice(0, 2, newColor);

The above is your code.

Before your code runs, the arr looks like this:
[‘DarkGoldenRod’, ‘WhiteSmoke’, ‘LavenderBlush’, ‘PaleTurqoise’, ‘FireBrick’]

after your code, it will look like this:
[[‘DarkSalmon’, ‘BlanchedAlmond’], ‘LavenderBlush’, ‘PaleTurqoise’, ‘FireBrick’]

does it seem correct?

1 Like

This Stack Overflow post helped me with adding multiple array values.

The tl;dr version of that post is…

The first parameter to splice is the index to start with, the second is the number of elements to remove, the remainder are elements to insert. So if you insert the same number as were removed, you end up replacing them.

So a solution to this challenge is…

function htmlColorNames(arr) {
  // change code below this line
  arr.splice(0, 2, 'DarkSalmon', 'BlanchedAlmond');
  // change code above this line
  return arr;
} 

If I’m not mistaken, we have exactly the same code:

function htmlColorNames(arr) {
// change code below this line
arr.splice(0, 2, ‘Darksalmon’, ‘BlanchedAlmond’);
// change code above this line
return arr;
}

Now it just so happens that mine doesn’t give me a check for the criteria:
``htmlColorNames should return [“DarkSalmon”, “BlanchedAlmond”, “LavenderBlush”, “PaleTurqoise”, “FireBrick”]

Is this really right, if so, is there a bug, or else; how to solve challenge?

Here you should have used spread operator that is …newColor and it would work.

Close, you’ve got 'Darksalmon'instead of 'DarkSalmon'.

oh, my, lord.


Thank you!

1 Like

No problem. I’ve lost count of the number of times I’ve been pulling my hair out over something not working only to eventually realise it’s a typo.

Happy coding. :grinning:

1 Like

I have a question: why it is arr.splice(0,2) and not (0,1)?

Following the rules of arrays it supposed to be like this if you have to return.

I know the way you wrote is the right one but it is not entry in my head because the normal array rule of 0,1,2…