Skip to content

closest

Finds the closest numeric value in an array.

Returns the array value nearest to n. Ties keep the earlier value (2.5 against [1, 2, 3, 4] gives 2), and an empty array gives undefined. Axes use it to snap a pointer position to the nearest tick or data value.

import {closest} from "@d3plus/math";

closest(7, [1, 5, 10]);
closest(8, [1, 5, 10]);
closest(2.5, [1, 2, 3, 4]);
closest(3, []);

Parameters

import {closest} from "@d3plus/math";
nrequirednumber

The number value to use when searching the array.

arrArray.<number>Default []

The array of values to test against.