Ryan
Ryan

Reputation: 15270

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

Upvotes: 8

Views: 9198

Answers (5)

Lukho Mdingi
Lukho Mdingi

Reputation: 548

I recently had to do something like this for an array of objects. This is what I went with:

const myArr = [
    { controlId: 1, value: 'alpha'},
    { controlId: 2, value: 'beta' },
    { controlId: 3, value: 'gamma' },
    { controlId: 4, value: 'delta'}
];

function getAllBefore(id) {
    const index = myArr.findIndex( ({ controlId }) => controlId === id);
    return myArr.filter((_, i) => i < index);
}

Upvotes: 1

Asadbek Eshboev
Asadbek Eshboev

Reputation: 111

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))

Upvotes: 2

MikeD
MikeD

Reputation: 382

Try something like this

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

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 21

McGarnagle
McGarnagle

Reputation: 102783

Use indexOf and slice:

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

Upvotes: 1

Related Questions