HomeLanguagesJavascriptLodash _.invertBy() Method

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.




// 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

5 COMMENTS

Most Popular

Dominic
32726 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7103 POSTS0 COMMENTS
Nicole Veronica
12241 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12328 POSTS0 COMMENTS
Shaida Kate Naidoo
7219 POSTS0 COMMENTS
Ted Musemwa
7476 POSTS0 COMMENTS
Thapelo Manthata
7200 POSTS0 COMMENTS
Umr Jansen
7176 POSTS0 COMMENTS