9

I just completed section1, and noticed that there isn't a method covered on how to push an item to the a specific location of the array. For example, if I wanted the array to show

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]

How would I be able to push in "Brooks Brothers" into the position [2] of the array suits, and shift the rest 1 down? Is there a built-in function in javascript similar to push that would enable me to do this?

I suppose I could always, with some diffculty:

function add (item, position){
    var length = suits.length;
    for(i = length -1; i >= position; i--){
        suits[length] = suits[i];
        length--;
    };
    suits[position] = item;
};

add("Brooks Brothers",2) //to add it to the middle
Kayaman
  • 70,361
  • 5
  • 75
  • 119

4 Answers4

24

There are no inbuilt function for this in JavaScript but you can simply do this using splice

var suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];

suits.splice(2, 0, "Brooks Brothers");

console.log(suits);

This would insert item X to index 2 of array suits, ["hearts", "clubs", "Brooks Brothers", "Brooks Brothers", "diamonds", "spades"]

Syntax

<array-name>.splice(<position-to-insert-items>,0,<item-1>,<item-2>,..,<item-n>)

Always pass second second argument as 0, because we don't want to delete any item from the array while splicing.

CodeIt
  • 3,248
  • 3
  • 24
  • 36
12

You can use Array.splice in order to insert item to Array at specific place.

const suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];

suits.splice(2, 0, 'newItem');

console.log(suits);
felixmosh
  • 26,970
  • 6
  • 57
  • 80
6

You can use the built-in Splice Function

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

1- To insert single value

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];

//1st param is insert index = 2 means insert at index 2
//2nd param is delete item count = 0 means delete 0 elements
//3rd param is new item that you want to insert
suits.splice(2, 0 , "Test");

console.log(suits);

2- To insert array into your suits array

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];

var newSuitsToInsert = ["test1", "test2","hello"];

    //1st param is insert index = 2 means insert at index 2
    //2nd param is delete item count = 0 means delete 0 elements
    //3rd param is new item that you want to insert
    //... is the spread syntax which will expand elements as one
    suits.splice(2, 0 , ...newSuitsToInsert);

    console.log(suits);
Hey24sheep
  • 1,142
  • 6
  • 16
2

You should use splice function

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]

suits.splice(2, 0, "somevalue");

console.log(suits);