1

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
        }
      }

1 Answer 1

1

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]

Sign up to request clarification or add additional context in comments.

1 Comment

It is now Working. When I read your reply; indexing individual items I couldn't help but kick myself. It makes sense to me now. I added a conditional i>0; and it works like a charm. Thank you for the quick reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.