Skip to content

Instantly share code, notes, and snippets.

@anuk79
Last active February 28, 2020 17:26
Embed
What would you like to do?
[JavaScript] Create a function to flatten a multi dimensional array with numbers, and remove any null/undefined value if present
function flattenArray(arr, res) {
let result = [];
for(let index = 0; index < arr.length; index++) {
const currentValue = arr[index];
if(Array.isArray(currentValue)) {
result = [...result, ...(flattenArray(currentValue))];
// we can also use concat method to achieve the same result
// result = result.concat(flattenArray(currentValue));
} else {
if(currentValue != null) {
result.push(currentValue);
}
}
}
return result;
}
const testArray = [1, 2, null, [4, undefined, [11, 10]], 6, [7, null, 0], null, 9];
const result = flattenArray(testArray);
console.log(result); // [1, 2, 4, 11, 10, 6, 7, 0, 9]
/** we also have flat method on Array prototype which flattens the Array, and we can provide a parameter to decide the depth of array till which it should be flattened.
Here, we will again need to write logic to remove the null/undefined values */
console.log(testArray.flat()) // [1, 2, null, 4, undefined, [11, 10], 6, 7, null, 0, null, 9]
/** if we do not know the depth of Array, and want it flattened then we can pass `Infinity` as argument */
console.log(testArray.flat(Infinity)) // [1, 2, null, 4, undefined, 11, 10, 6, 7, null, 0, null, 9]
// we can use filter to eliminate all null/undefined items from the flattened array
const result = testArray.flat(Infinity).filter(val => val != null);
console.log(result); // [1, 2, 4, 11, 10, 6, 7, 0, 9]
/** for more information on .flat method, visit below link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment