0

I know this is a bit on nonsense but I need to get the closest number out of 2 arrays or:

const myarr = [[12, 42], [12, 56], [30, 54]]

console.log(colsest_out_of_closest(myarr, [12, 50]))
9
  • 3
    What is the expected output? Commented Feb 15, 2023 at 18:12
  • 2
    the closest number to what? What have you tried? Commented Feb 15, 2023 at 18:12
  • 1
    Closest to the first number or the second number? [12, 56] is closest to the first number, but [30, 54] is closest to the second number. Commented Feb 15, 2023 at 18:15
  • the expected out output is [12, 56] Commented Feb 15, 2023 at 18:15
  • 1
    Why is [12,56] the expected output? Please shared what you have tried and explain the logic behind the expected output. Commented Feb 15, 2023 at 18:16

2 Answers 2

1

It looks like you want to find the smallest difference between both the min and the max.

const closest_out_of_closest = (arr, criteria) => {
  const [min, max] = criteria;
  let result, prevDiff = Number.MAX_VALUE;
  arr.forEach((item) => {
    const [localMin, localMax] = item;
    const diff = Math.abs(localMin - min) + Math.abs(localMax - max);
    if (diff < prevDiff) {
      prevDiff = diff;
      result = item;
    }
  });
  return result;
};

const myarr = [[12, 42], [12, 56], [30, 54]];

console.log(closest_out_of_closest(myarr, [12, 50])); // [12, 56]

Here is a reducer version that is less bytes, but still readable:

const closestRange = (arr, [min, max]) =>
  arr.reduce((acc, [lMin, lMax]) =>
    (diff => diff < acc.prev ? { result: [lMin, lMax], prev: diff } : acc)
    (Math.abs(lMin - min) + Math.abs(lMax - max)),
  { result: null, prev: Number.MAX_VALUE }).result;

console.log(closestRange([[12, 42], [12, 56], [30, 54]], [12, 50])); // [12, 56]

Sign up to request clarification or add additional context in comments.

Comments

1

You could check the absolute delta.

const
    getClosest = (a, b, t) => Math.abs(t - a) < Math.abs(t - b) ? a : b,
    getClosestPair = (target, array) => values.reduce((a, b) => 
        [0, 1].map(i => getClosest(a[i], b[i], target[i]))
    ),
    values = [[12, 42], [12, 56], [30, 54]],
    closest = getClosestPair([12, 50], values);
    
console.log(closest);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.