find nearest value in array in matlab in javascript

MATLAB

In MATLAB, you can use the min function to find the index of the value in an array that is closest to a given value. Here's an example:

A = [1, 3, 5, 7, 9];
target = 4.2;
[~, idx] = min(abs(A - target));
nearest_value = A(idx);
92 chars
5 lines

In this example, A is the array you want to search, target is the value you want to find the nearest value to, abs(A - target) calculates the absolute difference between A and target, min finds the minimum absolute difference, idx is the index of the value in A with the minimum absolute difference, and nearest_value is the value in A with the minimum absolute difference.

JavaScript

In JavaScript, you can use a similar approach to find the nearest value in an array. Here's an example:

let A = [1, 3, 5, 7, 9];
let target = 4.2;
let idx = A.reduce((prev, curr) => {
    return (Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev);
});
let nearest_value = A[idx];
190 chars
7 lines

In this example, A is the array you want to search, target is the value you want to find the nearest value to, reduce applies a function to each element of A to find the element with the minimum absolute difference, idx is the element with the minimum absolute difference, and nearest_value is the value in A with the minimum absolute difference. Note that in JavaScript, the idx variable stores the value of the nearest element, not the index of the nearest element.

gistlibby LogSnag