javascript array unwrap code example
Example 1: array flatten
const arr = [1, 2, [3, 4]];
// To flat single level array
arr.flat();
// is equivalent to
arr.reduce((acc, val) => acc.concat(val), []);
// [1, 2, 3, 4]
// or with decomposition syntax
const flattened = arr => [].concat(...arr);
Example 2: flatten an array in javascript
// Although this now may be an older version of how to faltten an
// array of arrays. I still want to post it so some may have an understanding
// of how it works
function falltenArray(arr) {
let result = [...arr];
let flattened = false;
let counter = 0;
while (flattened === false){
// checks to see if the element at the counter index is an array
if (Array.isArray(result[counter])){
// unpacks the current array element back into the array
result.splice(counter, 1, ...result[counter]);
// if so the counter should start at the beginning of the array
counter = 0;
} else {
counter += 1;
}
if (counter === result.length){
flattened = true;
}
}
return result;
}