Skip to content

Instantly share code, notes, and snippets.

@mlshv
Last active October 6, 2021 16:17
Show Gist options
  • Save mlshv/61b8f5b1e22bc60fe20ba8fbd22fec57 to your computer and use it in GitHub Desktop.
Save mlshv/61b8f5b1e22bc60fe20ba8fbd22fec57 to your computer and use it in GitHub Desktop.
Find and replace JavaScript function for arrays
export const replace = (array, index, value) => {
return [...array.slice(0, index), value, ...array.slice(index + 1)]
}
/**
* Finds and replaces an item inside an array
* @param {Array} array
* @param {Function} findPredicate Callback for Array.prototype.find
* @param {*|Function} replaceCallbackOrItem Any value: replaced value. Function: recieves old value as argument and should return a new value.
*
* @returns New array with replaced item
*/
export const findAndReplace = (array, findPredicate, replaceCallbackOrItem) => {
const index = array.findIndex(findPredicate)
if (index === -1) {
return array
}
if (typeof replaceCallbackOrItem === 'function') {
return replace(array, index, replaceCallbackOrItem(array[index]))
}
return replace(array, index, replaceCallbackOrItem)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment