Open In App

Lodash _.invertBy() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.invertBy() method is similar to _.invert() method except that the inverted object is generated from the results of running each element of object through iteratee. Also the corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value.

Syntax:

_.invertBy(object, iteratee)

Parameters:

This method accepts two parameters as mentioned above and described below:

  • object: It holds the object to invert every element.
  • iteratee: It holds the function that the method invoked per iteration.

Return Value:

This method returns the new inverted object.

Example 1: In this example, the code uses the Lodash library to invert an object by mapping values to keys and converting each key using a custom function.

Here, const _ = require(‘lodash’) is used to import the lodash library in the file.

javascript




// Requiring the lodash library
const _ = require("lodash");
      
// Original array
let object = { 'x': 3, 'y': 5, 'z': 3 };
 
// Using the _.invertBy() method
let invt_elem = _.invertBy(object);
 
// Printing the output
console.log(invt_elem);


Output:

{ '3': ['x', 'z'], '5': ['y'] }

Example 2: In this example, the code uses the Lodash library to invert an object by grouping keys based on their values using a custom grouping function.

javascript




// Requiring the lodash library
const _ = require("lodash");
      
// Original array
let object = { 'x': 3, 'y': 5, 'z': 3 };
 
// Using the _.invertBy() method
let invt_elem = _.invertBy(object, function(value) {
  return 'group' + value;
});
 
// Printing the output
console.log(invt_elem);


Output:

{ 'group3': ['x', 'z'], 'group5': ['y'] }

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.



Last Updated : 09 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads