Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active November 9, 2020 11:24
Show Gist options
  • Save sturmenta/d6979860da57e9a001fb4af107bbd81f to your computer and use it in GitHub Desktop.
Save sturmenta/d6979860da57e9a001fb4af107bbd81f to your computer and use it in GitHub Desktop.
remove object from array in javascript, add, and replace
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