Debug School

rakesh kumar
rakesh kumar

Posted on

How to count the specific word in array of object in react js

Requirement: i have to count how many answertwo in checkone array field in below screenshot

Image description

const count = data[0].checkone.filter(item => item.includes('answerone')).length;
Enter fullscreen mode Exit fullscreen mode

In controller

try 
      {       
        const myfeedback = await FeedbackModel.find({ 
      questionid: item }).exec();
        console.log(myfeedback);

      res.status(200).json({ myfeedback })  
      } 
Enter fullscreen mode Exit fullscreen mode

In front end clientside

<div>
              {myfeedback ?
                myfeedback.map((item) => (          

                  <div key={item.id} className="feedbox">                
                     <h5>Multiple Choice:</h5>
                    <ul><li>{item.answer_one}({item.checkone.filter(item => item.includes('answerone')).length})</li>
                    <li>{item.answer_two}({item.checkone.filter(item => item.includes('answertwo')).length})</li>
                    <li>{item.answer_three}({item.checkone.filter(item => item.includes('answerthree')).length})</li>
                    <li>{item.answer_four}({item.checkone.filter(item => item.includes('answerfour')).length})</li> 
                    <h5>Subjective:</h5>
                    <li>{item.textanswer !== null? <span>
              {item.textanswer.map((answer, index) => (
                <span key={index}>{answer}</span>
              ))}
            </span>:null}</li>                     
                    </ul>

                </div>
                ))
                : <p>No feedback data available</p>}  
          </div>
Enter fullscreen mode Exit fullscreen mode

Image description

output

Image description

Top comments (0)