Last active
January 11, 2018 07:00
-
-
Save Jiang-Xuan/79511b63d5ae9da6561266bae77b3e70 to your computer and use it in GitHub Desktop.
flatArray
This file contains 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
const foo = [{ | |
key: 'first' | |
}, { | |
key: 'second' | |
}, { | |
key: 'third' | |
}, { | |
key: 'more', | |
children: [{ | |
key: 'fourth' | |
}, { | |
key: 'fifth' | |
}, { | |
key: 'more', | |
children: [{ | |
key: 'sixth' | |
}, { | |
key: 'seventh' | |
}] | |
}] | |
}] | |
function flatArray(array, prop, decideFunc) { | |
if (Object.prototype.toString.call(array) !== '[object Array]') { | |
throw new TypeError('The type of first argument must be an array'); | |
} | |
if (typeof prop !== 'string') { | |
throw new TypeError('The type of second argument must be a string'); | |
} | |
if (decideFunc && Object.prototype.toString.call(decideFunc) !== '[object Function]') { | |
throw new TypeError('The type of third argument must be a function'); | |
} | |
let result = []; | |
array.map(item => { | |
if (!(prop in item)) { | |
result.push(item); | |
} else { | |
if (decideFunc && decideFunc(item)) { | |
const child = item[prop]; | |
const tmp = flatArray(child, prop, decideFunc); | |
result = [...result, ...tmp]; | |
} else { | |
result.push(item); | |
} | |
} | |
}); | |
return result; | |
} | |
flatArray(foo, 'children') | |
/* | |
[{ | |
key: 'first' | |
}, { | |
key: 'second' | |
}, { | |
key: 'third' | |
}, { | |
key: 'fourth' | |
}, { | |
key: 'fifth' | |
}, { | |
key: 'seventh' | |
}] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment