patternjavascriptMinor
Flattening array in Javascript
Viewed 0 times
arrayjavascriptflattening
Problem
I have implemented a solution to flatten an array of multiple levels in Javascript. I am just a newbie so forgive any mistakes. Could someone give me any tips to improve the code?
function streamrollArray(arr) {
var copyArr = arr;
var to_return = [];
while (true) {
if (copyArr.length <= 0) { return to_return; }
var head = copyArr[0];
to_return = to_return.concat(getValues(head));
//Chop head off since we have got all the values from it.
copyArr = copyArr.splice(1);
}
}
function getValues(arr) {
var copyArr = arr;
var to_return = [];
if (!Array.isArray(arr)) {
return arr;
}
while (true) {
//A head can contain multiples arrays inside it.
if (copyArr.length <= 0) { return to_return; }
var head = copyArr[0];
to_return = to_return.concat(getHead(head));
copyArr = copyArr.slice(1);
}
}
function getHead(head) {
//If its an array we break into it getting the head and keep checking.
while (Array.isArray(head)) {
head = head[0];
}
return head;
}Solution
I would think that this might be a problem best solved via recursion.
For example:
Also consider a more meaningful name for your function like
For example:
function flattenArray(arr) {
var result = [];
arr.forEach(function($val) {
if(Array.isArray($val)) {
result = result.concat(flattenArray($val));
} else {
result.push($val);
}
});
return result;
}Also consider a more meaningful name for your function like
flattenArray vs. steamrollArray. This better conveys what the function does. Look at your question title for example. You used Flattening array to describe your code not Steamrolling array.Code Snippets
function flattenArray(arr) {
var result = [];
arr.forEach(function($val) {
if(Array.isArray($val)) {
result = result.concat(flattenArray($val));
} else {
result.push($val);
}
});
return result;
}Context
StackExchange Code Review Q#156716, answer score: 3
Revisions (0)
No revisions yet.