我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
您也可以尝试新的Array.flat()方法。其工作方式如下:
let arr=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18“】,【”$22“】,[”$10“]].flat()控制台日志(arr);
flat()方法创建一个新数组,所有子数组元素递归地连接到其中,直到1层深度(即数组内部的数组)
如果您还想展平三维或更高维度的数组,只需多次调用flat方法。例如(三维):
设arr=[1,2,[3,4,[5,6]]].flat().flat;控制台日志(arr);
小心!
Array.flat()方法相对较新。像ie这样的旧浏览器可能没有实现该方法。如果你想让你的代码在所有浏览器上运行,你可能需要将你的JS转换成一个旧版本。检查MDN web文档的当前浏览器兼容性。
其他回答
适用于所有数据类型的递归版本
/*jshint esversion: 6 */
// nested array for testing
let nestedArray = ["firstlevel", 32, "alsofirst", ["secondlevel", 456,"thirdlevel", ["theinnerinner", 345, {firstName: "Donald", lastName: "Duck"}, "lastinner"]]];
// wrapper function to protect inner variable tempArray from global scope;
function flattenArray(arr) {
let tempArray = [];
function flatten(arr) {
arr.forEach(function(element) {
Array.isArray(element) ? flatten(element) : tempArray.push(element); // ternary check that calls flatten() again if element is an array, hereby making flatten() recursive.
});
}
// calling the inner flatten function, and then returning the temporary array
flatten(arr);
return tempArray;
}
// example usage:
let flatArray = flattenArray(nestedArray);
let arr = [1, [2, 3, [4, 5, [6, 7], [8, 9, 10, 11, 12]]]];
function flattenList(nestedArr) {
let newFlattenList = [];
const handleFlat = (array) => {
let count = 0;
while (count < array.length) {
let item = array[count];
if (Array.isArray(item)) {
handleFlat(item);
} else {
newFlattenList.push(item);
}
count++;
}
};
handleFlat(nestedArr);
return newFlattenList;
}`enter code here`
console.log(flattenList(arr));
CodeSandBox链接
我只使用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]
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]
看起来这看起来像是一份招聘工作!
处理多层嵌套处理空数组和非数组参数没有突变不依赖现代浏览器功能
代码:
var flatten = function(toFlatten) {
var isArray = Object.prototype.toString.call(toFlatten) === '[object Array]';
if (isArray && toFlatten.length > 0) {
var head = toFlatten[0];
var tail = toFlatten.slice(1);
return flatten(head).concat(flatten(tail));
} else {
return [].concat(toFlatten);
}
};
用法:
flatten([1,[2,3],4,[[5,6],7]]);
// Result: [1, 2, 3, 4, 5, 6, 7]