-3

I git this list of items and an array to hold 4 of them. When clicking on an item i want it to get pushed to the array, but the array should never be more or less than 4 in its length. So when clicking on one of the LI's i want to push that item to the array. and when the array is full (when the lenght is 4) i instead want the first element in the array to be swapped out to whatever next item that gets clicked is.

My markup looks similar to this:

        <ul>
            <li>val 1</li>
            <li>val 2</li>
            <li>val 3</li>
            <li>val 4</li>
            <li>val 5</li>
            <li>val 6</li>
            <li>val 7</li>
            <li>val 8</li>
            <li>val 9</li>
        </ul>
user2952238
  • 749
  • 2
  • 11
  • 36

1 Answers1

0

var ar=[];
function clickFunc(e){
    if(ar.length<4){
     ar.push(e.innerHTML);
    }
    else{
     ar.unshift(e.innerHTML);
     ar.pop();
    }
console.log(ar)
}
<ul>
            <li onclick="clickFunc(this)">val 1</li>
            <li onclick="clickFunc(this)">val 2</li>
            <li onclick="clickFunc(this)">val 3</li>
            <li onclick="clickFunc(this)">val 4</li>
            <li onclick="clickFunc(this)">val 5</li>
            <li onclick="clickFunc(this)">val 6</li>
            <li onclick="clickFunc(this)">val 7</li>
            <li onclick="clickFunc(this)">val 8</li>
            <li onclick="clickFunc(this)">val 9</li>
</ul>

u can unshift(),then pop() array.

Durga
  • 15,263
  • 2
  • 28
  • 52