Adding a value to the front of a NEW Array?

You are correct!

newArr = [element, … arr];
return newArr;

I must be getting tired :weary: Thank you @kevinSmithand thank you for all the help guys! Told you I’d be banging my head for this.

1 Like

Yeah, your function would have worked:

function addToFrontOfNew ( arr, element){
  arr.unshift(element); // adds element to front of array
  return arr.splice(); // returns NEW array with same values including new value at the front.
}

You just have to do a slice first (not *splice), before the unshift. Remember that when you pass arrays (or objects) to functions you are really passing the address. So that variable arr in the function is not a copy of the array, but a copy of the address so when you change that copy you are also changing the original. This is an important concept that gets lost on beginners. This is the same exact reason it is difficult to copy arrays.

Creating my own prototype is pretty advanced for the stage I’m currently at but will add it to my arsenal someday!

Yes, but I gave you the code. At the top of the file, you have:

Array.prototype.xUnshift = function(el) {
  let newArr = this.slice()
  newArr.unshift(el)
  return newArr
}

Then everywhere below that, those arrays will have the prototype built in. That is also essentially the code for a function to do it, but this would be replaced with a passed array variable. Or you could do it ES6.

Array.prototype.xUnshift = function(el) {
  return [el, ...this]
}