0

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
      }
    ]
1
  • Array.prototype.filter + Array.prototype.some Commented Oct 30, 2018 at 7:50

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.