Lodash _.flatten() 方法
Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。
Lodash.flatten()方法用于将数组展平到一层深度。
句法:
flatten( array )
参数:此方法接受包含简单数组或数组数组的单个参数数组。
返回值:该函数的返回类型为数组。
注意:在使用下面给出的代码之前,请使用命令npm install lodash
安装 lodash 模块。
示例 1:当给定二维整数数组时。
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)
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)
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)
输出:
示例 2:当给出对象数组的数组时。
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)
输出:
示例 3:当给出空数组时。
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)
输出: