@bemoje/arr-sorted-insertion-index

Find the array index of where to add an element to keep it sorted.

Usage no npm install needed!

<script type="module">
  import bemojeArrSortedInsertionIndex from 'https://cdn.skypack.dev/@bemoje/arr-sorted-insertion-index';
</script>

README

@bemoje/arr-sorted-insertion-index

Find the array index of where to add an element to keep it sorted.

Version

NPM version

Travis CI

dependencies

Dependencies

dependencies

Stats

NPM downloads Forks

Donate

Buy Me A Beer donate button PayPal donate button

Installation

npm install @bemoje/arr-sorted-insertion-index
npm install --save @bemoje/arr-sorted-insertion-index
npm install --save-dev @bemoje/arr-sorted-insertion-index

Usage


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
 */

Tests

Uses Jest to test module functionality. Run tests to get coverage details.

npm run test

API

Table of Contents

arrSortedInsertionIndex

Find the array index of where to add an element to keep it sorted.

Parameters
  • arr Array The array

  • element any The element for which to find its insertion index

  • compare (function | object)?

    • compare.numeric boolean Sort numerically. Defaults to lexicographic/alphabetic sort. (optional, default false)

    • compare.descending boolean Sort in descending order. Defaults to ascending order. (optional, default false)

    • compare.array boolean Sort arrays. Nested arrays are also compared recursively. (optional, default false)

    • compare.by (number | string | getter) Sort by either array index, a callback(element): any - or by object keys with dot-notation support. (optional, default undefined)

Returns number The insertion index

getter

Callback type definition.

Type: Function

Parameters
  • a any The value

Returns any The value to be compared