Yanic Yanic - 6 months ago 29
Javascript Question

Find most similar array of numbers

Let's say I have two arrays:

a=[168, 76, 62, 86]

b=[168, 80, 65, 90]


My input

[166.5, 75.5, 62, 86]


Now I want to get array "a" as my "result" because it is more similar to "a" than it is to "b".

How can I do that?

Answer Source

You could collect the absolute deltas and choose the one with the smaller error.

var array1 = [168, 76, 62, 86],
    array2 = [168, 80, 65, 90],
    input = [166.5, 75.5, 62, 86],
    error = [array1, array2].map(function (a) {
        return input.reduce(function (r, b, i) {
            return r + Math.abs(a[i] -b);
        }, 0);
    });
  
console.log(error); // [2, 13] take the first one with smaller error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download