Last active
November 9, 2020 11:24
-
-
Save sturmenta/d6979860da57e9a001fb4af107bbd81f to your computer and use it in GitHub Desktop.
remove object from array in javascript, add, and replace
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
export const arrayRemoveObject = (array: Object[] = [], toRemove: Object): Array<Object> => { | |
const tempArray = array.slice(); | |
if (JSON.stringify(tempArray).includes(JSON.stringify(toRemove))) { | |
return JSON.parse( | |
JSON.stringify(tempArray) | |
.replace(JSON.stringify(toRemove), '') | |
.split('},]') | |
.join('}]') | |
.split('",]') | |
.join('"]') | |
.split('[,') | |
.join('[') | |
.split(',,') | |
.join(','), | |
); | |
} | |
return tempArray; | |
}; | |
export const arrayAddObject = (array: Object[] = [], toAdd: Object, replace: Boolean = true): Array<Object> => { | |
let tempArray = array.slice(); | |
if (replace) tempArray = arrayRemoveObject(tempArray, toAdd); | |
tempArray.push(toAdd); | |
return tempArray; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment