Last active
October 6, 2021 16:17
-
-
Save mlshv/61b8f5b1e22bc60fe20ba8fbd22fec57 to your computer and use it in GitHub Desktop.
Find and replace JavaScript function for arrays
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
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