Merge branch 'master' of https://github.com/kriadmin/30-seconds-of-code
This commit is contained in:
@ -1,15 +1,16 @@
|
||||
### 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
|
||||
const sortedIndex = (arr,n) => {
|
||||
arr[0] > arr[1] ? (anarray = arr.reverse(),isReversed = true) : (anarray = arr,isReversed = false);
|
||||
val = anarray.findIndex( el => {
|
||||
return n <= el
|
||||
})
|
||||
return val === -1 ? arr.length : isReversed ? arr.length - val : val
|
||||
}
|
||||
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;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
Reference in New Issue
Block a user