0

Say you have this:

["10:00 PM", "10:15 PM", "10:30 PM", "10:45 PM", "11:00 PM"]

I would like to split or explode this array at "10:30 PM" and grab the remaining array:

["10:45 PM", "11:00 PM"]

Any ideas?

I could iterate through it and then match each result then build another array, i was thinking if there is a "built in" way.

4
  • I guess this is not precisely a duplicate, since the question is to remove elements up to and including one with a particular value, rather than removing one or some fixed number of elements from the beginning. Commented Sep 17, 2014 at 5:58
  • This question asks how to remove the first two elements, the dupe asks about removing one, and shows multiple approaches that could help the OP if he's ready to think a little. Commented Sep 17, 2014 at 6:03
  • If he was ready to think a little, he wouldn't have posted the question in the first place. Anyway, the questions doesn't ask how to remove the first two elements, it asks how to remove the elements up to and including the one with value "10:30 PM". Commented Sep 17, 2014 at 6:20
  • Actually, it does ask how to remove the first two elements ;-) As the OP said himself, he knows how to iterate through the array to find the matching element. He's looking for the correct builtin method to remove elements from the beginning of an array. Commented Sep 17, 2014 at 14:34

3 Answers 3

2
var times = ["10:00 PM", "10:15 PM", "10:30 PM", "10:45 PM", "11:00 PM"];

// without altering the array
var newTimes = times.slice(times.indexOf("10:30 PM") + 1);

// or, altering the array
times.splice(times.indexOf("10:30 PM") + 1);
Sign up to request clarification or add additional context in comments.

Comments

1

@sahbeewah's solution is good, another (destructive) possibility is

while (array.pop() !== '10:30 PM") { }

although you would also need to handle non-happy cases.

We could write a generalized analog to String#split using Array#reduce as follows:

function split_array(arr, delim) {
    return arr.reduce(function(result, elt) {
        if (delim === elt) {
            result.push([]);
        } else {
            result[result.length-1].push(elt);
        }
        return result;
    }, [[]]);
 }

Then

split_array(times, "10:30 PM") // [["10:00 PM", "10:15 PM"], ["10:45 PM", "11:00 PM"]]

so our result is split_array(times, "10:30 PM")[1].

An obvious extension would be to pass a function in place of delim to specify more general "delimiters".

Comments

0

You can use .splice() to do that.. like

var array = ["10:00 PM", "10:15 PM", "10:30 PM", "10:45 PM", "11:00 PM"];
var index = array.indexOf('10:30 PM');
var part2 = array.splice(index + 1);

console.log(array, part2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.