Files
30-seconds-of-code/snippets/js/s/sorted-index.md
2023-05-07 16:07:29 +03:00

730 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Insertion index in sorted array snippet javascript
array
math
apples 2020-10-22T20:24:30+03:00

Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting order.

  • Loosely check if the array is sorted in descending order.
  • Use Array.prototype.findIndex() to find the appropriate index where the element should be inserted.
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