javascript - When mapping through an array check next item property -


i'm mapping through array i.e.

contents.map((content) => {  switch(content.type) {    case: 1      console.log("type 1 , next type ..");    case: 2      console.log("type two")  } }) 

and can see in case 1 need grab type of next item. know possible using loop increment, need within map. i'm open suggestions using libraries lodash (wasn't able find in documentation).

array.prototype.map calls it's callback 3 parameters:

currentvalue // current element index // current index array // original array 

that means can of course access array via it's index within callback routine. instance:

contents.map((content, index, array) => {     switch(content.type) {         case 1:             console.log("type 1 , next type is: ", array[index+1] ? array[index+1].type : 'empty');             break;         case 2:             console.log("type two")             break;     } }); 

example: https://jsfiddle.net/z1sztd58/ reference: mdn


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -