Kanchon Gharami
Kanchon Gharami

Reputation: 949

add or delete from the beginning item of an array without using shift/unshift/loop in js

I need to write a simple js code to add or delete from the beginning item of an array without using shift/unshift/loop.

I was able to add items successfully but the delete operation can't be done.

My js code:

var array = [100, 200, 300]
var newFirstElement = 17
var array = [newFirstElement].concat(array) // add in begainning
console.log(array);

array = array.splice(0,1) // remove from begaining
console.log(array);

Output:

[ 17, 100, 200, 300 ]
[ 17 ]

How can I successfully delete item from the beginning of the array maintaining given conditions?

Upvotes: 0

Views: 171

Answers (2)

Samir
Samir

Reputation: 9

Kindly, no need to overwrite the array with the new splice

array.splice(0,1) // remove from begaining
console.log(array);

It will give you what you need: [100, 200, 300]

Upvotes: 1

TechySharnav
TechySharnav

Reputation: 5084

splice returns the removed elements. So, you need not to assign array variable to it.

var array = [100, 200, 300]
var newFirstElement = 17
var array = [newFirstElement].concat(array) // add in begainning
console.log(array);

array.splice(0, 1) // remove from begaining
console.log(array);

Upvotes: 1

Related Questions