Underscore.JS - flatten method



Syntax

_.flatten(array, [shallow])

flatten method flattens a nested array where nesting can be upto any length. If shallow is passed as true then array will be flatten upto first level only.

Example

var _ = require('underscore');

var list = [1, [2], [4], 5, [[6]]]
//Example 1: flatten list
result = _.flatten(list);
console.log(result)

//Example 2: flatten list to first level only 
result = _.flatten(list, true);
console.log(result)

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

[ 1, 2, 4, 5, 6 ]
[ 1, 2, 4, 5, [ 6 ] ]
underscorejs_processing_array.htm
Advertisements