Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
underscorejs

What is the invert() function in Underscore.js?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

The invert() method of the underscore.js module returns an inversion of the object. This means that the object key or property becomes the value and the object value becomes the key.

Syntax

_.invert(Object)
The syntax to call the invert() method

Parameters

Object: This is the object we want to invert the keys and values of.

Return value

The value returned is the same object, but with its values and keys inverted.

Note: If we want to use the invert() method, all values must be unique.

Example

// require underscore
const _ = require("underscore")
// create some objects
let obj1 = {one: 1, two: 2, three: 3, four: 4}
let obj2 = {name: "nodejs", package: "underscore", tag: "_"}
let obj3 = {a: "Apple", b: "Banana"}
let obj4 = {M: "Monday", T: "Tuesday", W: "Wednesday"}
// get inverted objects
console.log(_.invert(obj1))
console.log(_.invert(obj2))
console.log(_.invert(obj3))
console.log(_.invert(obj4))
Calling the invert() method of Underscore.js

Explanation

  • Line 2: We import the underscore package.
  • Lines 5–8: We create some objects.
  • Lines 11–14: We use the invert() method to invert the objects by making the keys the values, and the values the keys. Next, we print the values to the console.

RELATED TAGS

javascript
underscorejs

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring