Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return all previous items in a JavaScript array than a current value?

Let's say I have an array:

var myArr = new Array('alpha','beta','gamma','delta');

And that I want a function to return an array of all items before a given item:

function getAllBefore(current) {
    var myArr = new Array('alpha','beta','gamma','delta');
    var newArr = ???
    return newArr;
}

getAllBefore('beta'); // returns Array('alpha');
getAllBefore('delta'); // returns Array('alpha','beta','gamma');

What's the fastest way to get this? Can I split an array on a value? Do I have to loop each one and build a new array on the fly? What do you recommend?

What about if I wanted the opposite, i.e. getAllAfter()?

like image 812
Ryan Avatar asked Jul 02 '13 22:07

Ryan


1 Answers

function getAllBefore(current) {
    var myArr = new Array('alpha','beta','gamma','delta');
    var i = myArr.indexOf(current);
    return i > -1 ? myArr.slice(0, i) : [];
}

Get the index of the specified item. If found, .slice() from 0 to that index. If not found, return an empty array (or whatever other default value you like).

Note that .indexOf() is not supported (for arrays) in IE8 and older, but there is a shim you can use, or you could just use a simple for loop instead.

like image 145
nnnnnn Avatar answered Sep 27 '22 01:09

nnnnnn