Q:

Write a JavaScript program to get the lowest index at which value should be inserted into array in order to maintain its sort order

0

Write a JavaScript program to get the lowest index at which value should be inserted into array in order to maintain its sort order.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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;
};

console.log(sortedIndex([5, 3, 2, 1], 4));
console.log(sortedIndex([30, 50], 40));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now