Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thank you.

like image 209
Ricardo Rocha Avatar asked Jul 31 '18 10:07

Ricardo Rocha


People also ask

What does findIndex return if not found?

The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

How do you find the index of an element in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How does findIndex work in Javascript?

The findIndex() method executes the callbackFn function once for every index in the array, in ascending order, until it finds the one where callbackFn returns a truthy value. If such an element is found, findIndex() immediately returns the element's index.

How do you find the index of an object in an array in TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


3 Answers

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.

like image 67
Robby Cornelissen Avatar answered Nov 08 '22 13:11

Robby Cornelissen


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.

like image 22
hsz Avatar answered Nov 08 '22 13:11

hsz


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 >= 4 && item.fakeObject);
like image 33
31piy Avatar answered Nov 08 '22 14:11

31piy