Reputation: 1622
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
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
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
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