As you can see by all the answers, there are multiple ways to do this.
- One solution which is fixing the error in the original question:
function combine(array1d, element) {
return array1d.concat(element);
}
function reduce(array2d, reducerFn) {
let array1d = [];
for (let element of array2d) {
array1d = reducerFn(array1d, element);
}
return array1d;
}
let array2d = [[1, 2,],[3, 4]];
console.log(reduce(array2d, combine));
The difference here is the return array1d.concat(element); call instead of returning array1d and call .concat on it. concat is side-effect free, so it creates a new array instead of mutating the original one. I've also renamed combine in reduce to reducerFn to make it more clear that it could be changed to something else.
- Using reduce directly on the array (supported by almost all browsers)
let result = array2d.reduce(function (flattenedArray, element) {
return flattenedArray.concat(element);
}, []);
- Using
reduce and the spread operator instead of concat (no IE support - if you can drop it, you can also use Arrow functions):
let result = array2d.reduce(function (flattenedArray, element) {
return [...flattenedArray, ...element];
}, []);
- Using flatMap, the identity function can be used to flatten the array:
let result = array2d.flatMap(element => element);
- Using flat, which flattens (deeply) nested arrays the amount of dimensions it receives as an argument:
let result = array2d.flat();
- Using imperative style by creating a for loop for each dimension, fill the array in order - see answer by
flatMap and reduce, like concat, also return a new array, without mutating the original one. Since the original version looked more like trying to use a functional programming style to me, I guess these are a good addition to your toolbox. flatMap and flat are relatively recent additions to the language, so depending on the environments you need to support, you might end up using something else instead.
[1, 2, 3, 4]?[1, 2, 3, 4].array1d = combine(array1d, element);you could doarray1d = array1d.concat(element);(makingcombineobsolete)array1d = array1d.concat(element). Try this.concatdoesn't mutate the array, it creates a new one