Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - iterate through array until first occurence of specified element is found?

I have an array ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ]

I want to iterate through the array top-down, starting at the last yield and looking for the next occurence of an element not being yield (which is #page2).

This is what I have:

var longest = ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ],
    longestLen = longest.length;
for (i = longestLen-2; i>=0; i--) { 
     if ( longest[i] != "yield") {
          var gotoPage = longest[i];
          }
    }

I'm starting at i=5 (6 iterations) and checking if the element is not yield. However, the current way runs through all 6 iterations, so I end up with the page#1 instead of the #page2. I don't know how I can stop the iterations.

Using return did not work, what other means are there? Is lastIndexOf something I could use?

Thanks for help!

like image 604
frequent Avatar asked Dec 27 '22 12:12

frequent


1 Answers

Just because noone mentioned it so far, you can also go with ES5 .some() for that.

Looks like:

var longest = ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ],
    gotoPage;

longest.reverse().slice(1).some(function( elem ) {
    return (gotoPage = elem) !== "yield";
});

alert('goto page: ' + gotoPage);
like image 136
jAndy Avatar answered Apr 07 '23 20:04

jAndy