how to use the invoke function from the underscore library in javascript

The invoke function from the underscore library in JavaScript is used for invoking a method on each item in a collection of objects. Here's how to use it:

index.tsx
_.invoke(collection, methodName, *arguments)
45 chars
2 lines
  • collection: An array (or any other collection) of objects on which the method needs to be invoked.
  • methodName: The name of the method that needs to be invoked on each object of the collection.
  • *arguments: Any additional arguments to pass to the invoked method.

Here's an example of how to use invoke to invoke the toString method on each object in an array:

index.tsx
const numbers = [5, 10, 15];
const strings = _.invoke(numbers, 'toString'); // ['5', '10', '15']
97 chars
3 lines

In this example, the toString method is invoked on each number in numbers using invoke. The resulting array strings contains the string representation of each number in numbers.

You can also pass additional arguments to the invoked method. Here's an example of how to use invoke to invoke the slice method with additional arguments on each string in an array:

index.tsx
const strings = ['hello', 'world', 'underscore'];
const slicedStrings = _.invoke(strings, 'slice', 2, 4); // ['ll', 'rl', 'de']
128 chars
3 lines

In this example, the slice method is invoked on each string in strings with additional arguments 2 and 4 using invoke. The resulting array slicedStrings contains the sliced substrings of each string in strings.

gistlibby LogSnag