Get 5 closest elements to an element in array including that element

Issue

This Content is from Stack Overflow. Question asked by jorganinho

I am trying to get 5 closest elements to given element, including that element, in array. For example, if we have:

const arr = [1, 2, 3, 4, 7, 11, 12, 13, 15, 17]

and I want to get 5 closest elements to 11, it should return [4, 7, 11, 12, 13]. If i pass 1 it should return [1, 2, 3, 4, 7]. If I pass 15 it should return [11, 12, 13, 15, 17].



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?