Skip to content
Related Articles

Related Articles

Lodash _.invertBy() Method
  • Last Updated : 16 Sep, 2020

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.




// 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);

Output:

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

Example 2:




// 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);

Output:

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

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :