Sanjai kumar
Sanjai kumar

Reputation: 55

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

Upvotes: 0

Views: 44

Answers (2)

Reyno
Reyno

Reputation: 6505

You could make a combination of filter, map and join to get this working.

Example is not React but shows you how this can be achieved.

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

const state = [101, 105];

const getFruitNames = () => fruits
  .filter(({ code }) => state.includes(code)) // Get all fruit objects where the code is also in state
  .map(({ source }) => source) // Only return the source (name)
  .join(", "); // Turn into a comma seperated string

console.log(`My Fruits: ${getFruitNames()}`);

Upvotes: 2

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

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.

Upvotes: 1

Related Questions