This forum is now read-only. Please use our new forums! Go to forums
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
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.
Answer 5016d1cf29fdf700020029cb
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
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency