The sortedLastIndex
function from Lodash returns the index at which the provided value should be inserted into the given sorted array in order to maintain the sort order. It uses binary search to find the correct insertion index, so it can be more efficient than the native Array.prototype.indexOf
method for large arrays.
Here's an example of how to use sortedLastIndex
in JavaScript:
377 chars14 lines
In this example, we have an array of numbers called sortedArr
. We want to insert the number 35 into the array while maintaining the sort order. First, we use sortedLastIndex
to find the index where we should insert the value (in this case, between the 30 and 40 index positions). We then use the native splice
method to insert the value into the array at the correct index. Finally, we print the new sorted array to the console to verify the insertion was successful.
gistlibby LogSnag