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
const _ = require("lodash");
let object = { 'x' : 3, 'y' : 5, 'z' : 3 };
let invt_elem = _.invertBy(object);
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
const _ = require("lodash");
let object = { 'x' : 3, 'y' : 5, 'z' : 3 };
let invt_elem = _.invertBy(object, function (value) {
return 'group' + value;
});
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,
GeeksforGeeks 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!
Last Updated :
09 Nov, 2023
Like Article
Save Article