How to get the next element on Map function?

16,813

The callback of map method accepts 3 arguments:

  • current item value;
  • current item index;
  • the array map was called upon.

So, you could use index to get next element value:

var newArray  = myArray.map(function(value, index, elements) {
  var next = elements[index+1];
  // do something
});

or

var newArray  = myArray.map(function(value, index) {
  var next = myArray[index+1];
  // do something
});

Note, the value of next variable may be undefined. Test the variable, if need, to prevent errors.

Share:
16,813
Raul Blosfeld Wohnrath
Author by

Raul Blosfeld Wohnrath

Bachelor's in Computer Science, but still student. Junior Full Stack Web Developer with some experiences in React Native and Flutter. Now seeking for some studies in Security

Updated on June 21, 2022

Comments

  • Raul Blosfeld Wohnrath
    Raul Blosfeld Wohnrath almost 2 years

    I'm trying to make some coordinate plane functions on React native. But I'm having a problem that I don't know how to get the next element on my array.

    This is my array:

    [
    {"M":["0","0"]},
    {"H":"100"},
    {"V":"0"},
    {"H":"100"},
    {"V":"100"},
    {"H":"0"},
    {"V":"100"},
    {"H":"0"},
    {"V":"0"},
    ]
    

    This is my function:

    const rotate = (pathArray, angle) =>{
        if (angle > 0){
            let vCordinate;
            return pathArray.map((cordinate)=>{
                if(Object.entries(cordinate)[0][0] == "M"){
                    let mCordinate = Object.entries(cordinate)[0][1];
                    mCordinate[0] = (parseInt(mCordinate[0]) * Math.cos(angle)) - (parseInt(mCordinate[1]) * Math.sin(angle));
                    mCordinate[1] = (parseInt(mCordinate[1]) * Math.cos(angle)) + (parseInt(mCordinate[0]) * Math.sin(angle));
                    return {[Object.entries(cordinate)[0][0]]: mCordinate};
                }
                //LOGIC TO GET NEXT ELEMENT
                if(Object.entries(cordinate)[0][0] == "H"){
                    let hCordinate = Object.entries(cordinate)[0][1];
                    vCordinate = Object.entries(cordinate)[0][1]
                    return {[Object.entries(cordinate)[0][0]]: vCordinate};
                }
                if(Object.entries(cordinate)[0][0] == "V"){
                    return {[Object.entries(cordinate)[0][0]]: vCordinate};
                }
            })
        }
        return pathArray;
    }
    

    In this point I need to get the next element when I've hit "H".

    How to do this?