Skip to content

Instantly share code, notes, and snippets.

@mieradi
Created March 13, 2021 15:04
Show Gist options
  • Select an option

  • Save mieradi/eef9e2733f5eed99c1d4738bcdbff668 to your computer and use it in GitHub Desktop.

Select an option

Save mieradi/eef9e2733f5eed99c1d4738bcdbff668 to your computer and use it in GitHub Desktop.
// Example usage
const idArray = [
{ id: 1, title: "My First Title", body: "My first body text" },
{ id: 2, title: "My Second Title", body: "My second body text" },
{ id: 3, title: "My Third Title", body: "My third body text" },
];
const data = filterArrayOfObjectsByKey(idArray,'id', event.currentTarget.id, myData);
// pretend we are using React state
setIdArrayInState(data);
// you can also use it without defining a variable first
setIdArrayInState(filterArrayOfObjectsByKey(idArray,'id', event.currentTarget.id, myData));
// or imagine sending as a body prop on a request. i think this will work 🥴
fetch(someUrl,
{
method: "POST",
body: JSON.stringify(filterArrayOfObjectsByKey(idArray,'id', event.currentTarget.id, myData))
}
)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
// the function 😀
/**
* @name filterArrayOfObjectsByKey
* @desc description here
* @param { array } sourceArray the array of objects you're checking against
* @param { string } sourceArrayObjectKeyToCheck // the object key in your array you're looking to check for
* @param { string || number } valueToCheck // the value of the object you're looking for
* @param { object } objectToAddToSourceArray // the data you want to add to your sourceArray
* @returns returns array of objects or empty array
*/
function filterArrayOfObjectsByKey(
sourceArray: { [key: string]: string }[] | [],
sourceArrayObjectKeyToCheck: string,
valueToCheck: string | number,
objectToAddToSourceArray: { [key: string]: string | number }
): { [key: string]: string | number }[] | [] {
// check if the array contains the value you're looking for
if (
sourceArray.some(
(obj: { [key: string]: string | number }) =>
obj[sourceArrayObjectKeyToCheck] === valueToCheck
)
) {
// if the value exists, filter it out and return filtered array
return sourceArray.filter(
(obj: { [key: string]: string | number }) =>
obj[sourceArrayObjectKeyToCheck] !== valueToCheck
);
} else {
// of the value doesn't exists, add objectToAddToSourceArray to the source array
return [...sourceArray, objectToAddToSourceArray];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment