Push element to array if it doesnt exist or remove if it does exist
May 26, 2021 · 1 min readLucian CiobanuFor the next code sample, I have a material table with checkboxes on a column. The goal is to perform certain actions on the selected elements from the table so I am creating an array with the selected elements which needs to have push an element if it does not exist or remove it on selection if it already exists. I came across a wonderful example on StackOverflow which I want to keep for future reference. Here goes:
function filterArray(array, object, key) {
var index = array.findIndex(o => o[key] === object[key]);
if (index === -1) array.push(object);
else array.splice(index, 1);
return array;
}
const
fruits = [{ id: 1, fruit: "Apple" }, { id: 2, fruit: "Banana" }, { id: 3, fruit: "Pineapple" }];
console.log(filterArray(fruits, { id: 3, fruit: "Banana" }, "fruit"));
console.log(filterArray(fruits, { id: 4, fruit: "Strawberry" }, "fruit"));
Beautiful, isn't it?! The function combined with a click trigger will add and element to the array if it doesnt exist or it will remove it based on it's index if it already exists.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery