Skip to content

Instantly share code, notes, and snippets.

@patrickml
Created April 22, 2022 11:18
Show Gist options
  • Save patrickml/957cc7f53eb523b995e9c47742d8f72f to your computer and use it in GitHub Desktop.
Save patrickml/957cc7f53eb523b995e9c47742d8f72f to your computer and use it in GitHub Desktop.
Javascript Remove Matching Objects from list with .filter()
/**
Problem Statement
Javascript does not have a built in function that removes objects {} from an array with negitive conditions i.e. !=
*/
/* Example of problem */
const myArray = [ { a: 'b', 'b': 'c' }, { a: 'b', 'b': 'd' }];
const filter = { a: 'b', b: 'c'}
myArray.filter(({ a, b }) => a != filter.a && b != filter.b);
/**
at first glance this looks like it would work, however because both objects
within the array meet the first condition a != filter.a the second condition b != filter.b is never
checked. This results in a return of [] where we expect a return of [{ a: 'b', 'b': 'd' }]
*/
/**
Two ways of solving this are by creating any array which holds your conditions
[conditionA, conditionB] and checking if all of the values are True or False depending on which function you use
*/
/** Solution 1 Array.every
The benefit with this case is you get to use positive checks ===
*/
const myArray = [ { a: 'b', 'b': 'c' }, { a: 'b', 'b': 'd' }, { a: 'b', 'b': 'e' }, { a: 'a', 'b': 'e' }];
const filter = { a: 'b', b: 'c'}
myArray.filter(({ a, b }) => !([a === filter.a, b === filter.b].every(Boolean)))
const result = [
{
"a": "b",
"b": "d"
},
{
"a": "b",
"b": "e"
},
{
"a": "a",
"b": "e"
}
];
/** Solution 2 Array.some
The benefit with this solution is some should stop after finding one case which meets the condition limiting
the number of loops if you have many conditions
*/
const myArray = [ { a: 'b', 'b': 'c' }, { a: 'b', 'b': 'd' }, { a: 'b', 'b': 'e' }, { a: 'a', 'b': 'e' }];
const filter = { a: 'b', b: 'c'}
myArray.filter(({ a, b }) => ([a !== filter.a, b !== filter.b].some(Boolean)))
const result = [
{
"a": "b",
"b": "d"
},
{
"a": "b",
"b": "e"
},
{
"a": "a",
"b": "e"
}
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment