30秒学会 JavaScript 片段 · 2017年8月21日

30秒学会 JavaScript 片段 – sortedIndex

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

Check if the array is sorted in descending order (loosely).
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