9

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

3
  • 3
    Use indexOf to get the position of the first item that matches what you're looking for. Then use slice from 0 to that index Commented Jul 2, 2013 at 22:05
  • 1
    Use .indexOf() to find the match and .slice() to make a copy of part of the array. Commented Jul 2, 2013 at 22:05
  • No need for slice, just set the length to the index + 1 (as long as modifying the original is OK). :-) Also, Array.prototype.indexOf is ES5 so may need extra support for older browsers. Commented Jul 2, 2013 at 22:19

5 Answers 5

22
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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! What would I change to get getAllAfter(current)?
@Ryan myArr.slice(i + 1)
All after? return i > -1 ? myArr.slice(i+1) : myArr.slice(0); - that is, return from 1 after the index if the item is found, otherwise return a copy of the whole array if not found (or whatever other default you want for when not found; you could use return i > -1 ? myArr.slice(i+1) : []; to default to an empty array).
+1 for using ternary operators... I rarely see them in javascript and although some people hate then, for a simple either/or, I find it much easier to read.
@RobG - Yes, that requirement hasn't been spelled out, but I covered those options in my previous comment and in my answer. I don't really like using .slice(0, i<0 ? 0 : i) because it seems kind of a waste to use .slice() to return an empty array. Doing it as shown in my answer looks clearer to me, and also allows an easy change to return null or undefined should the requirement change...
|
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))

Comments

1

Use indexOf and slice:

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

3 Comments

what abount index of returning -1?
@PilgerstorferFranz no worries there, it would just return an empty array.
@McGarnagle: No, it returns everything but the last element then.
1

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

Comments

0

Try something like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.