Array items related to adding new item

Asked

Viewed 70 times

3

I own a array that has 10 items, for example:

var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

And, in my html, I have several buttons, with id’s, for example:

<button id="item_12">12</button>
<button id="item_27">27</button>
<button id="item_54">54</button>

However, I would like, when clicking on a button, to add the id in the array in the first item, and the others to move to the next item, for example (if I clicked on the id button = item_54):

var array_exemplo = ["item_54", "item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9"];

How can I do that?

1 answer

3


Use the method unshift inserting a new value at the beginning of the array:

    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    var button = document.getElementById("item_54");

    button.onclick = function(){

        array_exemplo.unshift(this.id);

    }

If you want to do this in HTML:

HTML

<input type="button" id="item_54" onclick="addId(this.id)">

JS

    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    function addId(Id){

        array_exemplo.unshift(Id);

    }
  • Perfect! I had no idea of the existence of unshift! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.