0

how do you filter out objects from an array of objects by the value of one key if this key is also included in an array of strings?

const objArr = [
{
identifiers: {id: 1, name: "X"}, 
char: {char1: a, char2: b}
},
{
identifiers: {id: 2, name: "Y"}, 
char: {char1: c, char2: d}
},
]

not filter out all objcts that have a name that is included in this arr:

with strArr = [
"X", "Z"
]

result:

const objArrAfterFilter = [
{
identifiers: {id: 2, name: "Y"}, 
char: {char1: c, char2: d}
},
]

1 Answers1

1

This should do the trick:

const objArr = [{
    identifiers: {id: 1, name: "X"}, 
    char: {char1: 'a', char2: 'b'}
},
{
    identifiers: {id: 2, name: "Y"}, 
    char: {char1: 'c', char2: 'd'}
},
];

strArr = ["X", "Z"]

filtered_array = objArr.filter((element)=>{
    return !strArr.includes(element.identifiers.name);
});

console.log(filtered_array)

Basically, just use the filter method in the array prototype, which returns a new list elements in objArr that satisfy the condition in the function.

The condition we're specifying is that the name of the identifier of the element should not be included within strArr, so the condition looks like this:

!strArr.includes(element.identifiers.name)

Robo Mop
  • 3,485
  • 1
  • 10
  • 23