You are viewing a single comment's thread. Return to all comments →
function closestNumbers(arr) { const sortedArray = [...arr].sort((a, b) => a - b); const startingPoint = sortedArray.splice(0, 2); return sortedArray.reduce((acc, element, index) => { const previosElement = index === 0 ? acc[1] : sortedArray[index - 1]; const currentDifference = Math.abs(element - previosElement); const existingDifference = Math.abs(acc[0] - acc[1]); if (currentDifference < existingDifference) return [previosElement, element]; if (currentDifference === existingDifference) return acc.concat(previosElement, element); return acc; }, startingPoint); }
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →