Skip to content

Instantly share code, notes, and snippets.

@eliashussary
Created February 13, 2018 16:33
Show Gist options
  • Save eliashussary/f6603b6515e0290abd3ae4bc29bfd1f7 to your computer and use it in GitHub Desktop.
Save eliashussary/f6603b6515e0290abd3ae4bc29bfd1f7 to your computer and use it in GitHub Desktop.
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.
/**
* 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' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment