Last Insertion Index in Sorted Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring the concept of finding the last insertion index in a sorted array. We will learn how to check if the array is sorted in descending order and how to use Array.prototype.reverse() and Array.prototype.findIndex() to find the appropriate last index where the element should be inserted. By the end of this lab, you will have a better understanding of how to maintain the sort order of an array.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28465{{"`Last Insertion Index in Sorted Array`"}} javascript/data_types -.-> lab-28465{{"`Last Insertion Index in Sorted Array`"}} javascript/arith_ops -.-> lab-28465{{"`Last Insertion Index in Sorted Array`"}} javascript/comp_ops -.-> lab-28465{{"`Last Insertion Index in Sorted Array`"}} javascript/array_methods -.-> lab-28465{{"`Last Insertion Index in Sorted Array`"}} end

Description of Last Insertion Index in Sorted Array

To find the highest index where a value should be inserted into an array in order to maintain its sort order, follow these steps:

  • First, loosely check if the array is sorted in descending order.
  • Then, use Array.prototype.reverse() and Array.prototype.findIndex() to find the appropriate last index where the element should be inserted.

Here is the code for the function:

const sortedLastIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr
    .reverse()
    .findIndex((el) => (isDescending ? n <= el : n >= el));
  return index === -1 ? 0 : arr.length - index;
};

And here is an example of how to use the function:

sortedLastIndex([10, 20, 30, 30, 40], 30); // 4

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Last Insertion Index in Sorted Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like