I tried to implement an array flatten function recursively. Here is the code:
JavaScript
x
19
19
1
function flatten(arr) {
2
var flatArr = [];
3
for (var i = 0; i < arr.length; i++) {
4
if (arr[i] instanceof Array) {
5
flatArr.concat(flatten(arr[i]));
6
} else {
7
flatArr.push(arr[i]);
8
}
9
}
10
return flatArr;
11
}
12
13
14
console.log(flatten([1, 2, 3, 4, [5]]));
15
/*
16
result: [1, 2, 3, 4]
17
expected: [1, 2, 3, 4, 5]
18
*/
19
But I don’t know why the result is not correct. Please help me explain it.
Advertisement
Answer
The
concat()
method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
flatArr.concat(...)
doesn’t change flatArr
… you need to assign it like so:
flatArr = flatArr.concat('flatten(arr[i]));
Here is a working example with 3 levels deep array:
JavaScript
1
16
16
1
function flatten(arr) {
2
var flatArr = [];
3
for (var i = 0; i < arr.length; i++) {
4
if (arr[i] instanceof Array) {
5
flatArr = flatArr.concat(flatten(arr[i]));
6
} else {
7
flatArr.push(arr[i]);
8
}
9
}
10
return flatArr;
11
}
12
13
var arr = [1,2,3,4,[5,6,[7,8]]];
14
var flatten = flatten(arr);
15
16
$('#result').html(JSON.stringify(flatten));
JavaScript
1
2
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<div id="result"></div>
You can read more about Array.concat function here