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.
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.
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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With