1

I'm trying to filter an array using the method from this post, but I can't seem to get it working. My setup is below, which I'm expecting to result in an empty array because the one object in the array matches the filter criteria, but it is resulting in the original array being returned in the console. Is there something here that I'm missing?

var myArr = [
    {
        link_source_id: "act_0",
        link_source_name: "Hello World!",
        link_target_id: "obj_1",
        link_target_name: "Document",
        link_type: "activity-object-input"
    }
]

var myFilter = {
    link_source_id: "act_0",
    link_target_id: "obj_1"
}

myArr = myArr.filter(function (item) {
  for (var key in myFilter) {
    if (
      item[key] === undefined ||
      item[key] !== myFilter[key]
    )
      return false;
  }
  return true;
});

console.log(myArr)
userNick
  • 503
  • 4
  • 7
  • 25

2 Answers2

0

here is an example

const obj = [
    {id:1 , name:"Alice"} , {id:1,name:"Bob"}
]

const arr = obj.filter((oneObj)=>{
    return (oneObj.id==1 && oneObj.name=="Alice")
})

console.log(arr); // will log [{id:1 , name:"Alice"}]
Ahmed Magdy
  • 1,054
  • 11
  • 16
0

I'll leave this up for others, but answer my own questions based on the comments in the OP. Swapping the true and false statements should resolve the issue:

var myArr = [
    {
        link_source_id: "act_0",
        link_source_name: "Hello World!",
        link_target_id: "obj_1",
        link_target_name: "Document",
        link_type: "activity-object-input"
    }
]

var myFilter = {
    link_source_id: "act_0",
    link_target_id: "obj_1"
}

myArr = myArr.filter(function (item) {
  for (var key in myFilter) {
    if (
      item[key] === undefined ||
      item[key] !== myFilter[key]
    )
      return true;
  }
  return false;
});

console.log(myArr)
userNick
  • 503
  • 4
  • 7
  • 25
  • 1
    both the `code-snippets` - in your question and answer are correct. One filter is `positive` (it filters out matches) and the other is `negative` (it filters out un-matched items). – Aakash Sep 20 '20 at 01:56