vishnu
vishnu

Reputation: 4599

Filter two arrays using the properties in Reactjs

I have two arrays and want to filter the array from another using reactjs. I want to display only checked=true and the value property in first array is equal to the listname in second array.

can anyone help to provide the sample code to do that?

Firstarray:

[
  {
    "listname": "Cash Deposit",
    "totalsuccess": "45"
  },
  {
    "listname": "Cash Withdrawl",
    "totalsuccess": "25"
  },
  {
    "listname": "Fund Transfer",
    "totalsuccess": "9"
  }
]

Second array:

[
      {
        "name": "txn",
        "value": "Cash Deposit",
        "checked": true
      },
      {
        "name": "txn",
        "value": "Cash Withdrawl",
        "checked": false
      }
    ]

Upvotes: 0

Views: 57

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282030

You can make use of filter with some

const a = [
      {
        "name": "txn",
        "value": "Cash Deposit",
        "checked": true
      },
      {
        "name": "txn",
        "value": "Cash Withdrawl",
        "checked": false
      }
    ]

const b = [
  {
    "listname": "Cash Deposit",
    "totalsuccess": "45"
  },
  {
    "listname": "Cash Withdrawl",
    "totalsuccess": "25"
  },
  {
    "listname": "Fund Transfer",
    "totalsuccess": "9"
  }
]

const res = a.filter(obj => {
   if(obj.checked) {
      return b.some(item => item.listname === obj.value);
   }
   return false;
})
console.log(res);

Upvotes: 2

Aseem Upadhyay
Aseem Upadhyay

Reputation: 4547

Here's my way to go about it.

firstArray.forEach( item => {
    secondArray.forEach( secondItem => {
       if(secondItem.checked && item.listname === secondItem.value) {
             //do your action here
         }
       })
})

You can use filter prototype, if you do not want to implement these loops manually

Hope it helps :)

Upvotes: 0

Related Questions