I got a simple question, been hours on it and can’t figuring out the solution. I got an array of object. I want to remove the object that has same values that a variable I pass.
My problem is that it removes all the objects, even those that are not similar to my variable.
Here is my code
function appSelect(variable) {
//we check if the object already exists in my array {id:x, value:y}
const found = myArray.find(obj => {
return (obj.id === variable.id && obj.value === variable.value);
});
if (found) {
//If find it, I want to remove it from my array
const filtered = myArray.filter(obj => {
return (obj.id !== variable.id && obj.value !== variable.value);
})
//Return empty array
}
I receive the value from a select form. For exemple I got myArray = [{id: 1, value: 12},{id: 2, value: 12},{id: 5, value: 12}] and variable = {id: 2, value: 12}
What I did wrong?
>Solution :
The reason is the code below:
return (obj.id !== variable.id && obj.value !== variable.value)
Which means if id or value is the same,then it will be filtered.
You can change it to
return !(obj.id === variable.id && obj.value === variable.value)
Full code:
function appSelect(variable) {
//we check if the object already exists in my array {id:x, value:y}
const found = myArray.find(obj => {
return (obj.id === variable.id && obj.value === variable.value);
});
if (found) {
//If find it, I want to remove it from my array
const filtered = myArray.filter(obj => {
return !(obj.id === variable.id && obj.value === variable.value);
})
//Return empty array
}