Files
30-seconds-of-code/snippets/sortedIndex.md
2017-12-31 20:32:51 +05:30

413 B

sortedIndex

Returns the lowest index at which value should be inserted into array in order to maintain its sort order

const sortedIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.findIndex(el => isDescending ? n >= el : n <= el);
  return index === -1 ? arr.length : index;
};
sortedIndex([5,3,2,1], 4); // 1
sortedIndex([30,50],40); // 1