How to use filter array of objects by 2 conditions with an arrow function in js? [duplicate]

Suppose I have an array like:

  const items=[{
        "taskType": "type2",
        "taskName": "two",
        "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
      },
      {
        "taskType": "type1",
        "taskName": "two",
        "id": "c5385595-2104-409d-a676-c1b57346f63e"
      }]

I want to have an arrow (filter) function that returns all items except for where taskType=type2 and taskName=two. So in this case it just returns the second item?

Answers:

Answer

You can try negating the condition in Array.prototype.filter()

const items=[{
        "taskType": "type2",
        "taskName": "two",
        "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
      },
      {
        "taskType": "type1",
        "taskName": "two",
        "id": "c5385595-2104-409d-a676-c1b57346f63e"
      }]

var res = items.filter(task => !(task.taskType == 'type2' && task.taskName == 'two'));

console.log(res);

Answer

You can use lodash's _.reject(). Use an object as a predicate, and define the properties and values to reject by:

const items= [{
  "taskType": "type2",
  "taskName": "two",
  "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
},
{
  "taskType": "type3",
  "taskName": "two",
  "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
},
{
  "taskType": "type1",
  "taskName": "two",
  "id": "c5385595-2104-409d-a676-c1b57346f63e"
}]

const result = _.reject(items, { taskType: "type2", taskName: "two" });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.