2

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
OiRc
  • 1,602
  • 4
  • 21
  • 60
  • 3
    Possible duplicate of [How to insert an item into an array at a specific index?](https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index) – Titouan56 Jun 20 '17 at 07:45
  • @Epitouille i don't want to delete the element of the specific index – OiRc Jun 20 '17 at 07:45
  • 1
    @OiRc Read the link Epitouille showed, it clearly shows how to insert not just replace. – Andy Donegan Jun 20 '17 at 07:46

5 Answers5

3

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)
brk
  • 48,835
  • 10
  • 56
  • 78
3

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

selvakumar
  • 634
  • 7
  • 16
3

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];
double-beep
  • 5,031
  • 17
  • 33
  • 41
Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37
2

Here is what you need :

array.unshift(7);
FabienChn
  • 938
  • 10
  • 17
1

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