DEV Community

Passionate Coder
Passionate Coder

Posted on • Updated on

JS Interview Problem : Create a new array by adding one element at the beginning and one element at the end of an given array.

let arr = [3,5,6,1]
Add 9 at the starting of arr and 19 at the end of arr using ES6.

This is very common problem statement which can be asked in Interview. Now a days questions from ES6 or higher is being asked to test latest knowledge of developer.

This Problem can be solved in one line with the help of javascript spread operator.

Soluion

let newArr = [9, ...arr, 19]

I have this will help someone

For more such question visit

Top comments (6)

Collapse
 
indoor_keith profile image
Keith Charles • Edited

This is a neat use of the spread operator, though I might first ask the interviewer if they want to add these two new items in place or not. If they want the new values to be within the original array rather than create a new array with the old and new values, then we'd still have to use shift and pop to mutate the original array.

Having the foresight to ask this simple question I believe would be more impressive to me as an interviewer than understanding ES6 features.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

I was going to mention something similar, as the solution presented here is actually creating a new array, rather than adding to the original array - which is what seems to have been requested

Collapse
 
passionate_coder profile image
Passionate Coder

Yes agree. I am going to update my question.
and yes we can use unshift and push for adding elements at the start and end of an array

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
indoor_keith profile image
Keith Charles

Oh haha right! Unshift and push to add. I think I subconsciously wrote the subtraction methods because of what I was in the middle of working on at the time πŸ˜…

Collapse
 
anshup7 profile image
Anshuman Upadhyay

arr.unshift(9); arr.push(19)