Merge branch 'master' of https://github.com/kriadmin/30-seconds-of-code
This commit is contained in:
@ -1,15 +1,16 @@
|
|||||||
### sortedIndex
|
### sortedIndex
|
||||||
|
|
||||||
Returns the lowest index at which value should be inserted into array in order to maintain its sort order
|
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.findIndex()` to find the appropriate index where the element should be inserted.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const sortedIndex = (arr,n) => {
|
const sortedIndex = (arr, n) => {
|
||||||
arr[0] > arr[1] ? (anarray = arr.reverse(),isReversed = true) : (anarray = arr,isReversed = false);
|
const isDescending = arr[0] > arr[arr.length - 1];
|
||||||
val = anarray.findIndex( el => {
|
const index = arr.findIndex(el => isDescending ? n >= el : n <= el);
|
||||||
return n <= el
|
return index === -1 ? arr.length : index;
|
||||||
})
|
};
|
||||||
return val === -1 ? arr.length : isReversed ? arr.length - val : val
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
Reference in New Issue
Block a user