如何在JS中为以下内容编写函数:获取所有元素的子数组:
这些测试应通过:
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]);
发布于 2022-04-11 17:57:51
首先,使用indexOf
查看项目是否在列表中。如果不是的话,filter
会拿出比sort
更小的东西来获得下一个最大值,然后使用indexOf
来找到它的索引。最后,使用slice
获取数组的部分:
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);
};
您可以删除对indexOf
的第一个调用,并通过将<
更改为<=
获得相同的结果。
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);
};
https://stackoverflow.com/questions/71831895
复制相似问题