Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript Return the lowest index at which a value should be inserted into an array once it has been sorted (either in ascending or descending order).
We have to write a function that returns the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted (either in ascending or descending order). The returned value should be a number.
For example, Let’s say, we have a function getIndexToInsert() −
getIndexToInsert([1,2,3,4], 1.5, ‘asc’) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
Likewise,
getIndexToInsert([20,3,5], 19, ‘asc’) should return 2 because once the array has been sorted in ascending order it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).
Therefore, let’s write the code for this function −
Example
const arr = [20, 3, 5];
const getIndexToInsert = (arr, element, order = 'asc') => {
const creds = arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if(val Output
The output in the console will be −
1
2
Advertisements
