Closest Numbers

  • + 0 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);
    }