Lodash _.invertBy() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc.

The _.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: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var 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);

chevron_right


Output:

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

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

full-stack-img

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.