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()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With