HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Searching for the closest "stop" elements surrounding a start point

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thesearchingelementspointstartstopsurroundingforclosest

Problem

This code works but is there a simple / better way to do this?

It starts from a particular point (starthere) in the array, looks for first stop value to the left of start point, and the first stop to the right side.

Basically returns the closest values' positions to a start point both sides. (I'll make this a function.)

var arr = ['f','f','stop','stop','f','f','starthere','f','f','f','stop','stop','f','f','f','f'];

var i = arr.indexOf('starthere');
while (i--) {
    if (arr[i] == 'stop') {
        document.write(i + '');
        break;
    }
}

for (var i = arr.indexOf('starthere'); i < arr.length; i++) {
    if (arr[i] == 'stop') {
        document.write(i);
        break;
    }

}


Returns 310

Solution

There is an overload of .indexOf that takes a second parameter indicating the starting location for the search. That can be used to find the stop after starthere. Then you can use .slice to grab the part of the array before starthere with lastIndexOf to find the stop that comes before:

var i = arr.indexOf('starthere');
var stopafter = arr.indexOf('stop', i);
var stopbefore = arr.slice(0, i).lastIndexOf('stop');
document.write(stopbefore + '' + stopafter);

Code Snippets

var i = arr.indexOf('starthere');
var stopafter = arr.indexOf('stop', i);
var stopbefore = arr.slice(0, i).lastIndexOf('stop');
document.write(stopbefore + '</br>' + stopafter);

Context

StackExchange Code Review Q#23519, answer score: 2

Revisions (0)

No revisions yet.