Search code examples
javascriptarraysreactjsrendering

How do i render the Array value by comparing another array in ReactJs


I have certain array from props which is given below

this.props.fruits= [
  {
    source: "Apple",
    code: 101,
  },
  {
    source: "banana",
    code: 105,
  },
  { source: "Mango",
    code: 107,
  },
];

in my state I have to save the code only for send it for back-end my state is given below

this.state ={
   myfruits:[101,105]
}

I have to render the myfruits name in the DOM element example rendering DOM element

My Fruits : Apple , banana

Solution

  • You can use a combination of filter and map method,

    this.props.fruits.filter((fruit) => this.state.myfruits.includes(fruit.code))
              .map((fruit) => fruit.source)
    

    This should solve your problem. You can read more about map and filter here.