Home > database >  How to Find the Previous element in a mapped react function
How to Find the Previous element in a mapped react function

Time:06-25

I am having trouble targeting the previous element in a map function in react. When the previous element in an object array is not equal to the current I want to change the ID tag in HTML. I have been unsuccessful in comparing these two object array elements to each other. I have tried for loop & Mapping and seem to keep getting undefined or NAN.

I am unsure if this is even the right way to approach something like this. Not finding much on the web to help me either. Thank you for the help.

Here is how the Array Is Setup.

Array(4) [ {…}, {…}, {…}, {…}]


1: Object { id: 2, productName: "Zirconium Flap Disc, 4 1/2 x 7/8 x 40 Grit, Pk 5", … }
​
2: Object { id: 3, productName: "Zirconium Flap Disc, 4 1/2 x 7/8 x 60 Grit, Pk 5", … }
​
3: Object { id: 4,  productName: "Zirconium Flap Disc, 4 1/2 x 7/8 x 80 Grit, Pk 5", … }
​
4: Object { id: 5,  productName: "Zirconium Flap Disc, 4 1/2 x 7/8 x 120 Grit, Pk 5", … }

Trying to compare the Product Name In the first objects array to the productName in the Second object Array and So on. 1 Compares to 2, 2 compares to 3, 3 compares to 4 so on.

1.
products.map((item,i)=>{
return(
  <div className="pwrap" key={i} id={item[i].productName !== item[i-1].productName ? "line" : null}>
)

})
 

2. 
 const compare = ()=>{
        for(let i=0; i < props.products.length; i  ){
            let current = props.products[i]
            let pre = current[-1].productName
            return pre
        }
      }

CodePudding user response:

You have a bug in your first snippet, you are trying to index individual items instead of the array. It should be:

 products.map((item,i)=>{
    return(
      <div className="pwrap" key={i} id={products[i].productName !== products[i-1].productName ? "line" : null}>
    )

})

Though you'll need to add some conditional logic to make sure you don't index products[-1]

  • Related