'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()?



Solution 1:[1]

Use indexOf and slice:

newArr = myArr.slice(0, myArr.indexOf(current));

Solution 2:[2]

javascript slice array

// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]

// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]

array cut only last 5 element

 arr.slice(Math.max(arr.length - 5, 0))

Solution 3:[3]

Try something like this

var index = myArr.indexOf('beta');
var before = myArray.slice(0, index);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 McGarnagle
Solution 2 Asadbek Eshboev
Solution 3 MikeD