I am working on developing a function that can handle an array containing arrays, literals, or even objects and flatten it into a one-dimensional array. An example of valid input would be [5, [2, 3], 7, [9, 0, 1]]
, which should produce the output [5, 2, 3, 7, 9, 0, 1]
.
Here is my current code for achieving this task. While it works fine, I am looking to optimize it further for efficiency while ensuring compatibility with ES5.
function flattenArray(list) {
var result = [];
for (var index = 0; index < list.length; index++) {
result.push(list[index] instanceof Array ? list[index] : [list[index]]);
}
return [].concat.apply([], result);
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));