Open In App

Lodash _.flatten() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.flatten() method is used to flatten the array to one level deep and it returns a new flattened array.

Syntax:

_.flatten( array );

Parameter:

  • array that holds a simple array or array of arrays.

Return Value:

The return type of this function is an array.

Example 1: In this example, er are flattening the array to a single level by the use of the _.flatten() method.

Javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [[1, 2], [4, 5], [7, 8]]
 
// Using _.flatten() method
let newArray = _.flatten(array1);
 
// Printing original Array
console.log("original Array1: ", array1)
 
// Printing the newArray
console.log("new Array: ", newArray)


Output:

Example 2: In this example, er are flattening the array of object to a single level by the use of the _.flatten() method.

Javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [[{ "a": 1 }],
[{ "b": 2 }, { "c": 3 }]]
 
// Using _.flatten() method
let newArray = _.flatten(array1);
 
// Printing original Array
console.log("original Array1: ", array1)
 
// Printing the newArray
console.log("new Array: ", newArray)


Output: 

Example 3: In this example, er are flattening the empty array to a single level by the use of the _.flatten() method.

Javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [[], [[[]]], [[]], []]
 
// Using _.flatten() method
let newArray = _.flatten(array1);
 
// Printing original Array
console.log("original Array1: ", array1)
 
// Printing the newArray
console.log("new Array: ", newArray)


Output:



Last Updated : 20 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads