Last active
July 7, 2017 03:24
-
-
Save mir4ef/e7d5a44a089c27238270ee97f7809b0f to your computer and use it in GitHub Desktop.
Flatten a multi dimensional array to 1D array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* @method flattenArray | |
* @description A method to convert multi dimensional arrays to 1D arrays | |
* @param {Array} arr - The multi D array that needs to be flattened (converted to 1D) | |
* @param {String} [key] - An object key that will be used to flatten an array of | |
* nested objects (e.g. "[ { key: [ val1, val2, ..., valN ] }, { key: [ val1, val2, ..., valN ] } ]") | |
* @param {Boolean} [remove] - Flag to indicate whether or not to delete object's children if | |
* they are not need it after flattening (e.g. if true, will remove "key: [ val1, val2, ..., valN ]" after it is being flattened) | |
* @return {Array} Flattened array | |
*/ | |
function flattenArray(arr, key, remove) { | |
if (!Array.isArray(arr)) { | |
console.warn(`${new Date()}: the passed argument is not an array:`, arr); | |
return arr; | |
} | |
const result = arr.reduce((prev, curr) => { | |
const isObject = !!curr[key]; | |
const nestedItem = isObject ? curr[key] : curr; | |
const isArray = Array.isArray(nestedItem); | |
let finalArr = (isObject || !isArray) ? prev.concat(curr) : []; | |
if (isArray) { | |
if (isObject) { | |
finalArr = finalArr.concat(flattenArray(nestedItem, key, remove)); | |
if (remove) { | |
delete curr[key]; | |
} | |
} else { | |
// pass the key in case a deeper nested object needs to be flattened | |
finalArr = prev.concat(flattenArray(nestedItem, key, remove)); | |
} | |
} | |
return finalArr; | |
}, []); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment