Thursday, October 16, 2025
HomeLanguagesJavascriptLodash _.flatten() Method

Lodash _.flatten() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.
The Lodash.flatten() method is used to flatten the array to one level deep.

Syntax:

flatten( array )

Parameter: This method accepts single parameter array that holds simple array or array of arrays.

Return Value: The return type of this function is array.

Note: Please install lodash module by using command npm install lodash before using the code given below.

Example 1: When 2D array of Integers is given.

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: When array of arrays of object is given.

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: When empty array of arrays is given.

Javascript




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


Output:

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS