'All elements after first occurrence of closest element or first nearest by element
How would you write a function in JS for the following: Get the subarray of all elements:
- after and including the first occurrence of the searched element
- or after and including the first number greater than the searched element.
These tests should pass:
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 1)).toEqual([1, 3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 2)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 3)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 1, 4, 5], 2)).toEqual([3, 5, 1, 4, 5]);
Solution 1:[1]
First, use indexOf to see if the item is in the list. If not, filter out anything less than, sort that to get next biggest, then use indexOf to find the index of that. Finally, use slice to get the part of the array:
const elementsStartingFrom = (haystack, needle) => {
let idx = haystack.indexOf(needle);
if (-1 == idx) {
const tmp = haystack.filter(i => i > needle).sort((a, b) => a - b).at(0);
idx = haystack.indexOf(tmp);
}
if (idx == -1) return null;
else return haystack.slice(idx);
};
You could remove the first call to indexOf and get the same result by changing the < to <=:
const elementsStartingFrom = (haystack, needle) => {
const tmp = haystack.filter(i => i >= needle).sort((a, b) => a - b).at(0);
const idx = haystack.indexOf(tmp);
return (idx == -1) ? null : haystack.slice(idx);
};
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 | Johnny Mopp |
