Ricardo Rocha
Ricardo Rocha

Reputation: 16226

Use findIndex, but start looking in a specific position

I have the following extract of code:

private getNextFakeLinePosition(startPosition: number): number{
        return this.models.findIndex(m => m.fakeObject);
}

This function returns me the index of the first element which has the property fakeObject with the true value.

What I want is something like this, but instead of looking for the all items of the array, I want to start in a specific position (startPosition).

Note: This is typescript but the solution could be in javascript vanilla.

Upvotes: 18

Views: 9446

Answers (4)

31piy
31piy

Reputation: 23859

A vague, but working solution would be to skip the indices until we reach the start index:

let startIndex = 4;
array.findIndex((item, index) => index >= startIndex && item.fakeObject);

Upvotes: 4

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

The callback to findIndex() receives the current index, so you could just add a condition that way:

private getNextFakeLinePosition(startPosition: number): number {
    return this.models.findIndex((m, i) => i >= startPosition && m.fakeObject);
}

Not the most efficient solution, but should be OK as long as your array is not too large.

Upvotes: 13

Zbysek Voda
Zbysek Voda

Reputation: 81

In this case i would probably use for loop. It doesn't add overhead to slice array and avoids unnecessary indices check.

const findStartFromPos = <T>(predicate: (e: T) => boolean, array: T[], startFrom: number): number => {
  for (let i = startFrom; i < array.length; i++) {
    if (predicate(array[i])) {
      return i;
    }
  }

  return -1;
};

Upvotes: 8

hsz
hsz

Reputation: 152216

You can try with slice:

private getNextFakeLinePosition(startPosition: number): number {
  const index = this.models.slice(startPosition).findIndex(m => m.fakeObject);
  return index === -1 ? -1 : index + startPosition;
}

It'll slice your input array and find the index on a subarray. Then - at the end, just add the startPosition to get the real index.

Upvotes: 8

Related Questions