how to use the ntharg function from lodash in javascript

The nthArg function from Lodash returns a new function which returns the nth argument it receives. The index of the first argument is 0.

Here is an example of how to use it:

index.tsx
const nthArg = require('lodash/nthArg');

function foo(a, b, c) {
  console.log(nthArg(1)(a, b, c));
}

foo(1, 2, 3);
// output: 2
131 chars
9 lines

In this example, we require the nthArg function from Lodash and define our own function foo. The nthArg(1) part creates a new function that returns the second argument. In the foo function, we pass three arguments to nthArg(1) and log the result to the console.

We could also use nthArg with an array of arguments:

index.tsx
const nthArg = require('lodash/nthArg');

function bar(args) {
  console.log(nthArg(1)(...args));
}

bar([1, 2, 3]);
// output: 2
130 chars
9 lines

In this example, we define a function bar that accepts an array of arguments. Then we use the spread syntax ...args to pass the elements of the array as separate arguments to nthArg(1).

Note that the nthArg function works similarly to the _.at method from Lodash, which allows you to get values from an array by passing an array of indices.

gistlibby LogSnag