OiRc
OiRc

Reputation: 1622

Insert in a specific position on array without deleting the element in JS

I have an array like this:

var array = [3,5,6,2,1];

I want to insert 7 inside the first position without deleting 3 so the resulting array would be this:

array = [7,3,5,6,2,1];

Any suggestion on how to achieve this?

Upvotes: 2

Views: 4107

Answers (5)

Afshin Ghazi
Afshin Ghazi

Reputation: 2990

Use the Splice method:

var array = [3, 5, 6, 2, 1];
array.splice(0, 0, 7);

array.splice('index', 'replace or not', 'item to insert');

=> [7, 3, 5, 6, 2, 1];

array.splice(3, 0, 7); => [3, 5, 7, 6, 2, 1];

Upvotes: 5

brk
brk

Reputation: 50291

Assuming you want to enter only in first position.

You can use unshift

var x = [3, 5, 6, 2, 1];
x.unshift(7);
console.log(x)

If the element(which is to be insert) is inside another array, Spread_operator can come handy

var a = [7];
var x = [...a, 3, 5, 6, 2, 1];
console.log(x)

Upvotes: 3

Brunet Rémi
Brunet Rémi

Reputation: 11

To put something inside the first position, you can use "unshift"

<script type="text/javascript">
var tab=new Array("Apple", "Pineapple", "Cherry");
tab.unshift("Banana", "Peach")
document.write(tab.join(", "));
</script>

And you get :

Banana, Peach, Apple, Pineapple, Cherry

Upvotes: 1

FabienChn
FabienChn

Reputation: 968

Here is what you need :

array.unshift(7);

Upvotes: 2

selvakumar
selvakumar

Reputation: 654

Splice method will be used for this. array.splice(0, 0, 7);

Upvotes: 3

Related Questions