Find the array index of where to add an element to keep it sorted.
npm install @bemoje/arr-sorted-insertion-index
npm install --save @bemoje/arr-sorted-insertion-index
npm install --save-dev @bemoje/arr-sorted-insertion-index
import arrSortedInsertionIndex from '@bemoje/arr-sorted-insertion-index'
/**
* FIND THE INDEX OF WHERE TO ADD AN ELEMENT TO KEEP IT SORTED
*/
const alpha = ['a', 'b', 'd', 'e']
arrSortedInsertionIndex(alpha, 'c')
//=> 2
/**
* ACCEPTS A CUSTOM COMPARATOR FUNCTION
* Compares numerically
*/
const numeric1 = [0, 1, 3, 4, 5]
arrSortedInsertionIndex(numeric1, 2, (a, b) => {
return a - b
})
//=> 3
/**
* ALSO TAKES ADVANCED COMPARATOR BUILDER OPTIONS
*/
const numeric2 = [0, 1, 3, 4, 5]
arrSortedInsertionIndex(numeric, 2, {
numeric: true,
})
//=> 3
/**
* DESCENDING EXAMPLE
*/
const descending = [5, 4, 3, 2, 0]
arrSortedInsertionIndex(descending, 1, {
numeric: true,
descending: true,
})
//=> 4
/**
* To see more examples of using the comparator builder, visit:
* https://github.com/bemoje/bemoje-arr-sort-comparator
*/
Uses Jest to test module functionality. Run tests to get coverage details.
npm run test
Find the array index of where to add an element to keep it sorted.
-
arr
Array The array -
element
any The element for which to find its insertion index -
-
compare.numeric
boolean Sort numerically. Defaults to lexicographic/alphabetic sort. (optional, defaultfalse
) -
compare.descending
boolean Sort in descending order. Defaults to ascending order. (optional, defaultfalse
) -
compare.array
boolean Sort arrays. Nested arrays are also compared recursively. (optional, defaultfalse
) -
compare.by
(number | string | getter) Sort by either array index, a callback(element): any - or by object keys with dot-notation support. (optional, defaultundefined
)
-
Returns number The insertion index
Callback type definition.
Type: Function
a
any The value
Returns any The value to be compared