Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * fillBlanks takes an array with falsy/null values, and fills them with the previous value in the array.
- * If null values appear without a previous value, you can use nullReplace to autofill it.
- * @example
- * const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
- * fillBlanks(arr)
- * // => [ null, null, 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
- * @example
- * const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
- * fillBlanks(arr, "replaced")
- * // => [ 'replaced', 'replaced', 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
- * @function fillBlanks
- * @param {array} arr - the input array
- * @param {string} [nullReplace=null] - the replacement value when a null value is encountered
- * @returns {string[]}
- */
- function fillBlanks(arr, nullReplace = null) {
- const hasValue = val => (val || val === 0 ? true : false)
- return arr.reduce((acc, val, idx) => {
- if (hasValue(val)) {
- acc.push(val)
- } else {
- const hasPrevValue = hasValue(acc[idx - 1])
- const prevVal = hasPrevValue ? acc[idx - 1] : nullReplace
- acc.push(prevVal)
- }
- return acc
- }, [])
- }
- // Example:
- const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
- fillBlanks(arr)
- // => [ null, null, 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
- fillBlanks(arr, "replaced")
- // => [ 'replaced', 'replaced', 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
Add Comment
Please, Sign In to add comment