Adding a value to the front of a NEW Array?

Adding a value to the front of a NEW Array?
0.0 0

#1

What am I missing? .concat() adds a value into a new array, while .unshift() adds one to the front of the same array. I’ve tried

function addToFrontOfNew ( arr, element ) {
let newArray = arr.unshift(element);
return newArray.slice();
}

// or

function addToFrontOfNew(arr, element) {
let newArray = arr.concat(element);
if ( newArray.indexOf(element) > 0 ){
newArray[0] === element;
}
return newArray;
}

and many others . I know it’s something really simple. The only resources I’ve found talked about simply adding one to the front OR adding to a new one, but not adding a value to the front of a new array. You don’t have to show me the snippet, if you can explain the idea I’ll try and piece it together from there. Thanks!


#2

#3

Those are two different functions.

newArr = arr1.concat(arr2)

In this example, a new array is created and assigned to newArr. This is important: arr1 and arr2 are unchanged.

But unshift actually changes the array:

myArr.unshift(127)

myArr is now a different array with the number 127 added to the front. There is no need to assign it.


#4

Yes I tried .unshift(), it changes the current array but does not create a new array, just adds a value to the beginning of the old one.


#5

Yes, unshift returns the number of elements in the array:

let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = arr1.concat(arr2)

console.log(arr1)
// [1, 2, 3]

console.log(arr2)
// [4, 5, 6]

console.log(arr3)
// [1, 2, 3, 4, 5, 6]


let myArr = ['pear', 'orange', 'apple']
let x = myArr.unshift('banana')

console.log(myArr)
// ['banana', 'pear', 'orange', 'apple']

console.log(x)
// 4

but not adding a value to the front of a new array.

If you are trying to create a new array, then you can do it a couple ways. One is just to use concat. The other is to use slice:

let newArr = myArr.slice().unshift(127)

The slice method will create a shallow copy of the array.


#6

I tried that solution also, I too thought it would work but it only succeeds in creating a new array, but not adding the value to front or work for empty arrays. Thanks for the replies everyone, I’ll post my answer when I figure it out. Here are the instructions (just practice, not classwork)

/*
Write a function called “addToFrontOfNew”.

Given an array and an element, “addToFrontOfNew” returns a new array containing all the elements of the given array, with the given element added to the front.

Important: It should be a NEW array instance, not the original array instance.

var input = [1, 2];
var output = addToFrontOfNew(input, 3);
console.log(output); // --> [3, 1, 2];
console.log(input); --> [1, 2]
*/


#7

Did you want a solution or did you want to figure it out yourself?


#8

You can do this with a spread operator.


#9

Good question haha.

I guess I just want to know why these

arr.slice().unshift(element);

//or

let newArray = array.unshift(element);
return newArray.slice();

aren’t working, or what I may have missed thats not coming to mind. .concat() will add the value to a new array, is there like a sort method or something I’m missing?


#10

For the arr.slice().unshift(7) it will return what unshift returns since it is the right-most operation , not the new array

And the second one calls slice on what unshift returns which is not an array (in this case)

You’re basically there, just a slight tweak


#11
Array.slice()

returns all numeric properties/indeces between two given integers. This works on Strings or Arrays as they by nature use numeric indeces.

Array.unshift()

alters the array it is used on. It inherits the context of the array, and actually modifies the property values of the array. It is the equivalent of doing this

let array = [1,2,3,4]; // WE HAVE OUR ARRAY
// WE WANT TO REMOVE THE FIRST ENTRY, SO LETS 'UNSHIFT' ALL VALUES OVER TO THE LEFT.

for( let i = 1; i < array.length; i++ ){
  array[i - 1] = array[i]; // MOVE ALL INDECES AFTER FIRST ONE OVER TO THE LEFT BY ONE INDEX
  delete array[array.length - 1]; // IMPERATIVELY REMOVE VALUE FROM ARRAY
}
let array = [1,2,3,4];

// SLICE(2) WILL RETURN [2,3,4] AND UNSHIFT WILL REMOVE 2 AND RETURN IT, ALTERING THE ORIGINAL ARRAY AND RETURNING A TRUTHY (MEANING IT RETURNS TRUE IN AN IF STATEMENT) VALUE
array.slice(1).unshift();

#12

I tried setting the argument to .slice() instead but no dice. It’s only passing 1 of the 4 tests, the one that checks for a new array. I can post all of the test cases if anyone is interested, but I know I’m going to bang my head for how simple this should be.

@ Emgo-Dev

Trying to retain the values from the first array, but just add the value passed through the function into a new array containing all original values plus the new value at the front.


#13

Just don’t chain any methods. I.e. A().B().C(). Call one function, then the other, on a new line. Maybe it will make things more clear.


#14

I see, I got mixed up, in that case you can do the same thing, just move the index values over to the right. When you are ‘shifting’ values you always want to ‘pull’ them, that way you won’t override any values you need to iterate too.

let array = [1,2,3,4];

for( let i = array.length; i >0; i-- ){
  array[i] = array[i - 1];
}
delete array[0];

array // [<1 empty slot>, 1, 2, 3, 4];
// CONSOLE DISPLAYS CUSTOM TEXT FOR INTERRUPTIONS IN NUMERICAL PROPERTY/INDECES THAT WE SEE IN ARRAYS/STRINGS.
// THE FIRST VALUE DOES NOT CONTAIN ANY VALUE BECAUSE THE 0 property is removed entirely. BASICALLY I DESTROYED THE 0 INDEX. MUAHAHA.
array[0] = someNewValue;

unshift() just performs an operation on an array, kinda like a tic tac container just returns one tic tac, not a whole new container. That would be breaking the law of equivalent exchange.

Now slice() however would be like cutting open that darn plastic container, and just taking only the tic tacs you wanted. Now maybe you decide you want just one more tic tac, so you grab one and add it to your hand, that is an unshift(). No new container, you broke it, but you added a tic tac to your hand.


#15

Sorry, yes, my code won’t quite work. You can break it into two steps:

let newArr = arr.slice()
newArr.unshift(127)

The other option of course is just to define your own Array prototype method:

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

let newArr = arr.xUnshift(127)

#16

This would be easier if you were very clear about what it is you want. I think you might consider taking a moment to explain exactly what it is you are trying to do. Explain the intended input and the expected output. Show a few examples.


#17

Of course, there is also the ES6 solution with a spread operator:

let arr = [1, 2, 3]

let newArr = [127, ...arr]

console.log(arr)
// [1, 2, 3]
console.log(newArr)
// [127, 1, 2, 3]

#18

So if I use .slice() without an argument shouldn’t it return a new array with all of the same values?

@kevinSmith

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

I’m creating a function addToFrontOfNew that accepts 2 parameters ( arr, element) that when invoked returns the element placed at the front of a new array. I was thinking something like this:

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.
}

Everything else has been a crapshoot, mostly passing function test checking for new arrays but they don’t add the new value but I’ll keep hammering away to I get to something.


#19

The problem with using unshift is it alters the original array passed into the function before you attempt to return a new copy of it. There’s no point at that point. Might as well return the original arr.unshift.


#20

@kevinSmith literally gave you the answer 3 different ways.