# LeetCode: Find K Closest Elements Solution

Sort with custom comparator

## Approach

From MDN Web Doc for Array.prototype.sort():

If

compareFunction(a, b)
returns a value > than 0, sort
b
before
a

Steps:

• Sort the array by the main criteria
• Get first
k
elements
• Sort ascending

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} arr3 * @param {number} k4 * @param {number} x5 * @return {number[]}6 */7var findClosestElements = function (arr, k, x) {8  return arr.sort(compareFunction(x)).slice(0, k).sort(compareFunctionGt)9}10
11const compareFunction = x => (a, b) => {12  const [absAx, absBx] = [Math.abs(a - x), Math.abs(b - x)]13  return absAx < absBx || (absAx === absBx && a < b) ? -1 : 014}15
16const compareFunctionGt = (a, b) => a - b```

## References

Array.prototype.sort() (MDN Web Docs)

leetcode

array

sorting

## Next Post

LeetCode: Count Vowels Permutation

Jul 4, 2021

Memoized recursion

## Previous Post

Toptal Interview Process Guide and Review

Jul 2, 2021

Journey of a non-native English-speaker developer on looking for a remote opportunity

Search Posts