I am trying to find a way to check my array and add or remove objects based on name criteria.
var array = [{name: "pet"}, {name: "animals"}]
var newObject = {name: "pet"}
var updatedArray = array.filter(el => el.name !== newObject.name)
console.log(updatedArray)
I am expecting to remove the object and my updatedArray to look like [{name: "animals"}]
Your existing code will just remove it if it's there. It doesn't try to remember whether it was found and add it if it isn't.
To do that, I'd use findIndex
:
function removeOrAdd(array, obj) {
var index = array.findIndex(el => el.name === newObject.name)
if (index === -1) {
// Not found, add it
array.push(newObject);
} else {
// Found, remove it
array.splice(index, 1);
// or create a new array instead of splicing:
//array = array.filter(function(_, i) { return i !== index);
}
}
findIndex
calls a callback for each array entry until the callback returns a truthy value, then stops and returns that index; if the callback never returns a truthy value, findIndex
reutrns -1 when it runs out of entries.
Live Copy:
function removeOrAdd(array, obj) {
var index = array.findIndex(el => el.name === newObject.name)
if (index === -1) {
// Not found, add it
array.push(newObject);
} else {
// Found, remove it
array.splice(index, 1);
// or create a new array instead of splicing:
//array = array.filter(function(_, i) { return i !== index);
}
}
var array = [{name: "pet"}, {name: "animals"}]
var newObject = {name: "pet"}
console.log("before", array);
removeOrAdd(array, newObject); // Found, so it was removed
console.log("after1", array);
removeOrAdd(array, newObject); // Not found, so it was added
console.log("after2", array);
.as-console-wrapper {
max-height: 100% !important;
}
@Liam
some()
can't work here because the code uses the found index to remove the element i.earray.splice(index, 1);
You only remove one copy, instead of all matching objects.
@Liam Array#some is older than Array#findIndex
@Paulpro - That was how I read the question. Always possible I'm reading it wrong, but I don't think so.
Fair enough; OP didn't really specify. I just thought his attempt with Array#filter was because he wanted to remove every match. As long as objects are only added with addOrRemove I suppose there can never be duplicates anyway.