简体   繁体   中英

How to compare array objects present in two different React states

I want to compare object arrays present in two different React states. My state values are something like below:

review1 = [{name: John, Title: Manager},{name: Peter, Title: Engineer}, {name: Serena, Title: Supervisor}]
review2 = [{personName: John, ismanager: yes}, {name: Peter, ismanager: no}, {personName: Serena, ismanager: yes},{personName: John, ismanager:yes}]

Now I want to get count of people who are manager. If multiple then count should increase. In this case John is manager for two position then count for John is 2 and for Peter 0 and Serena 1

I am trying below function but it doesn't work as expected.

let filter = this.state.review1.map(elem=>elem.personName)
count = this.state.review2.map(data=> data.name).reduce((n,x) =>n +(x === filter.personName && data.ismanager === "yes"),null)

<div> John: {ismanger.count}, Serena: {ismanager.count}, Peter: {ismanager.count} </div> 

You could count directly the manager with the condition.

 var review2 = [{ personName: 'John', ismanager: 'yes' }, { personName: 'Peter', ismanager: 'no' }, { personName: 'Serena', ismanager: 'yes' }, { personName: 'John', ismanager: 'yes' }], count = Array.from( review2.reduce((m, { personName, ismanager }) => m.set(personName, (m.get(personName) || 0) + (ismanager === 'yes')), new Map), ([name, count]) => ({ name, count }) ); console.log(count); 

I guess we only need to do it over review2 array right? Try this.

Demo At: playcode

review2 = [{personName: 'John', ismanager: 'yes'}, {name: 'Peter', ismanager: 'no'}, {personName: 'Serena', ismanager: 'yes'},{personName: 'John', ismanager:'yes'}]

const countMap = review2.reduce((accum, person) => {
  const isPersonName = !!person.personName;
  const name = isPersonName ? person.personName : person.name;
  if (accum[name] && person.ismanager === 'yes') {
    accum[name]++;
  } else if (person.ismanager === 'yes') {
    accum[name] = 1;
  }

  return accum;
}, {})

console.log(countMap);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM