reference map value in the same map (JavaScript)

I am certain my issue here is not knowing what to call what I’m trying to do here, so any help with that would be appreciated, but I’d like to map over an array and create two values, where the first one refers to the prior value… is that possible?

arr =[1,2,3]
arr.map((el, i) => ({ 
   x: el, 
   y: 5, 
   z: y[i] + 2 // is there a way I can write this so I can refer to y ???
}))

any help appreciated!

24 thoughts on “reference map value in the same map (JavaScript)”

  1. If I understand it correctly. You may want to generate the y outside of the object, and then refer to it inside:

    const arr = [1, 2, 3];
    arr.map((el, i) => {
       const y = 'something';   // calculate y
       return { 
          x: el, 
          y,              // refer to y
          z: y[i] + 2     // refer to y
       };
    });
    
    Reply
  2. Is this what you’re looking for?

    const arr = [1, 2, 3]
    
    const newArr = arr.map((currentValue, currentIndex) => {
      const previousValue = currentIndex > 0 ? arr[currentIndex - 1] : 0
    
      const output = {
        x: currentValue,
        y: 5,
        z: previousValue + 2
      }
    
      return output
    })
    
    Reply

Leave a Comment