Toggling an array of filters What follows is a piece of code that essentially toggles an array of filters (if the filter doesnt exist it adds it, if it does, it removes it).

What would you suggest is the best way to write the following imperative approach declaratively?

var selectedFilters = [ {name:"SomeName"} , ... ]
var inputFilter = {name:"OtherName"};

var indexFound = -1;
for (let i = 0; i &lt; selectedFilters.length; i++) {
    if (selectedFilters[i].name === inputFilter.name) {
        indexFound = i;
    }
}

if (indexFound != -1) {
    selectedFilters.splice(indexFound, 1);
} else {
    selectedFilters.push(inputFilter);
}


An idea would be to use filter first to weed out the item if it exists by name, then if the resulting array is equal to the original, push. But it still doesnt feel right.
Pure V State

There are two ways you can do this.

Pure

The first functional pure method first copies the array, then checks if the item to toggle exists then depending on that result adds or removes the item. Making sure that the added item is a copy, not a reference. It has no side effects but requires additional memory and CPU cycles.

const toggleItem = (itemDesc, items, prop = "name") =&gt; {
    items = [...items]; 
    const index = items.findIndex(item =&gt; itemDesc[prop] === item[prop]);
    index &gt; -1 ? items.splice(index, 1) : items.push({...itemDesc});
    return items;
}


State

The second does not create a new array and keeps all references It is "functionally" impure and ensures that the changed state is available to all references to the original. It is considerably quicker and uses less memory.

const toggleItem = (itemDesc, items, prop = "name") =&gt; {
    const index = items.findIndex(item =&gt; itemDesc[prop] === item[prop]);
    index &gt; -1 ? items.splice(index, 1) : items.push(itemDesc);
    return items;
}