我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
要在一行中展平二维阵列,请执行以下操作:
[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]
其他回答
有一个令人困惑的隐藏方法,它在不改变原始数组的情况下构造一个新数组:
var oldArray=[[1],[2,3],[4];var newArray=Array.prototype.contat.apply([],oldArray);console.log(newArray);//[ 1, 2, 3, 4 ]
这是我的版本。它允许您将复杂的对象展平,可以在更多场景中使用:
输入
var input = {
a: 'asdf',
b: [1,2,3],
c: [[1,2],[3,4]],
d: {subA: [1,2]}
}
Code
功能如下:
function flatten (input, output) {
if (isArray(input)) {
for(var index = 0, length = input.length; index < length; index++){
flatten(input[index], output);
}
}
else if (isObject(input)) {
for(var item in input){
if(input.hasOwnProperty(item)){
flatten(input[item], output);
}
}
}
else {
return output.push(input);
}
};
function isArray(obj) {
return Array.isArray(obj) || obj.toString() === '[object Array]';
}
function isObject(obj) {
return obj === Object(obj);
}
用法
var output = []
flatten(input, output);
输出
[“asdf”,1,2,3,1,2,3,4,1,2]
更简单和直接的方法;可选择深压平;
const flatReduce = (arr, deep) => {
return arr.reduce((acc, cur) => {
return acc.concat(Array.isArray(cur) && deep ? flatReduce(cur, deep) : cur);
}, []);
};
console.log(flatReduce([1, 2, [3], [4, [5]]], false)); // => 1,2,3,4,[5]
console.log(flatReduce([1, 2, [3], [4, [5, [6, 7, 8]]]], true)); // => 1,2,3,4,5,6,7,8
只有没有lodash的最佳解决方案
let flatten = arr => [].concat.apply([], arr.map(item => Array.isArray(item) ? flatten(item) : item))
您可以使用array.prototype.reduce()和array.protocol.contat()展平数组
var data=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18”】,【”$22“】,【“$10”】,“$15”】、【”$3“】,[”$75“],[”$5“],“$100”]、【”$7“】、【“$3”】、“$75”],“$5”]]。reduce(函数(a,b){返回a.concat(b);}, []);console.log(数据);
相关文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce