This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Allan
almost 12 years

Section 1: How to "push' a new item to the middle of an array?

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

Answer 50082f9e6786a00002030fe9

0 votes

Permalink

You would have to do a loop to move them down one space or put :

var suits = [“hearts”,”clubs”, “diamonds”,”spades”]; suits[4] =”spades” ; suits [3] = “diamonds”; suits[2] = “Brooks Brothers”; console.log(suits[0],suits[1],suits[2],suits[3],suits[4]);

That’s the only way I know how to do it.

points
Submitted by mckinsey2
over 11 years

Answer 5016d1cf29fdf700020029cb

0 votes

Permalink

splice is used for this aswell. When the number of elements to remove is 0 you can instead specify items to be inserted into the array:

myarray.splice(2,0,'one','two'); 

see here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

points
Submitted by nipheon
over 11 years