Lodash _.flatten() Method
Last Updated :
20 Oct, 2023
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
const _ = require( "lodash" );
let array1 = [[1, 2], [4, 5], [7, 8]]
let newArray = _.flatten(array1);
console.log( "original Array1: " , array1)
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
const _ = require( "lodash" );
let array1 = [[{ "a" : 1 }],
[{ "b" : 2 }, { "c" : 3 }]]
let newArray = _.flatten(array1);
console.log( "original Array1: " , array1)
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
const _ = require( "lodash" );
let array1 = [[], [[[]]], [[]], []]
let newArray = _.flatten(array1);
console.log( "original Array1: " , array1)
console.log( "new Array: " , newArray)
|
Output:
Share your thoughts in the comments
Please Login to comment...