how to use the sortedlastindexof function from lodash in javascript

_.sortedLastIndexOf is a function from the Lodash library that returns the index of the last occurrence of a provided value in an array, after it has been sorted in ascending order.

Here's an example of how to use this function:

index.tsx
const _ = require('lodash');  // import Lodash library

const arr = [2, 3, 5, 5, 7, 7, 7, 9];

const valueToFind = 7;  // value to find in the array
const sortedArr = _.sortBy(arr);  // sort the array in ascending order

const index = _.sortedLastIndexOf(sortedArr, valueToFind);

console.log(index);  // Output: 6
315 chars
11 lines

In this example, we have an array arr with some values. We want to find the index of the last occurrence of the value 7 in this array after it has been sorted in ascending order. So we first use the .sortBy() method from Lodash to sort the array in ascending order and store it in sortedArr.

We then pass the sorted array sortedArr and the value to find valueToFind into the _.sortedLastIndexOf() function, which returns the index of the last occurrence of valueToFind in the array. The resulting index is stored in the index variable, which we log to the console.

The output is 6, which is the index of the last occurrence of 7 in the sorted array.

gistlibby LogSnag