How would you write a function in JS for the following: Get the subarray of all elements:
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]);
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);
};