我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
如果你使用lodash,你可以使用它的flatten方法:https://lodash.com/docs/4.17.14#flatten
lodash的优点是它还具有使数组变平的方法:
i) 递归地:https://lodash.com/docs/4.17.14#flattenDeep
ii)多达n层嵌套:https://lodash.com/docs/4.17.14#flattenDepth
例如
const _ = require("lodash");
const pancake = _.flatten(array)
其他回答
我只使用ES6回答这个问题,假设深度阵列是:
const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];
如果您知道或猜测阵列的深度不超过7这样的数字,请使用以下代码:
const flatArray = deepArray.flat(7);
但如果你不知道深度数组的深度,或者你的JavaScript引擎不支持像react原生JavaScriptCore那样的flat,请使用下面的JavaScript reduce函数:
const deepFlatten = arr =>
arr.reduce(
(acc, val) =>
Array.isArray(val)
? acc.concat(deepFlatten(val))
: acc.concat(val),
[]
);
这两种方法都返回以下结果:
["1", "a", "b", 2, "4", 3, "c", 5]
另一种方法是使用jQuery$.map()函数。从jQuery文档:
该函数可以返回一个值数组,该数组将被展平为完整数组。
var source = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
var target = $.map(source, function(value) { return value; }); // ["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
我有一个简单的解决方案,不用在特殊的js函数中使用。(如减少等)
const input = [[0, 1], [2, 3], [4, 5]]
let flattened=[];
for (let i=0; i<input.length; ++i) {
let current = input[i];
for (let j=0; j<current.length; ++j)
flattened.push(current[j]);
}
ES6的纯粹魔力
const flat = A => A.reduce((A, a) => Array.isArray(a) ? [...A, ...flat(a)] : [...A, a], []);
function flatten(input) {
let result = [];
function extractArrayElements(input) {
for(let i = 0; i < input.length; i++){
if(Array.isArray(input[i])){
extractArrayElements(input[i]);
}else{
result.push(input[i]);
}
}
}
extractArrayElements(input);
return result;
}
// let input = [1,2,3,[4,5,[44,7,8,9]]];
// console.log(flatten(input));
// output [1,2,3,4,5,6,7,8,9]