'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.
Solution 1:[1]
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.
Solution 2:[2]
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);
Solution 3:[3]
Really old one but the easiest way would probably be
const startingIndex = 1;
[
{label: 'a'},
{label: 'b'}
]
.slice(startingIndex)
.findIndex(({ label }) =>
label.toLowerCase().startsWith(labelToFinds.toLowerCase())
)
Solution 4:[4]
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | 31piy |
| Solution 3 | Alexander Sasha Shcherbakov |
| Solution 4 | Zbysek Voda |
