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()?
indexOfto get the position of the first item that matches what you're looking for. Then useslicefrom 0 to that index.indexOf()to find the match and.slice()to make a copy of part of the array.