Home Ask Login Register

Developers Planet

Your answer is one click away!

Ilja February 2016

When mapping through an array check next item property

I'm currently mapping through an array i.e.

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

And as you can see in case 1 I need to grab type of next item. I know that this is possible using for loop with i increment, but need to do it within a map. I'm open for suggestions using libraries like lodash (wasn't able to find anything in the documentation).

Answers


jAndy February 2016

Array.prototype.map calls it's callback actually with 3 parameters:

currentValue // current element
index // current index
array // original array

That means you can of course access the array via it's index within a callback routine. For instance:

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

Example: https://jsfiddle.net/z1sztd58/ Reference: MDN


Ashwin Balamohan February 2016

First of all, Array.prototype.map requires you to return the mapped value, which you aren't doing.

In a simple example:

const primes = [2, 3, 5, 7, 11, 13];

const primesSquared = primes.map((prime) => {
  return prime * prime;
});

Array.prototype.map takes three arguments:

  • element: the current array element

  • index: the index of the current element within the array

  • array: the entire array

You've also got a syntax error in your switch statement. Note the position of the : in the case statement in the example below.

You could accomplish what you're trying to do with something like the following:

const newArray = oldArray.map((elem, index, array) => {
  switch(elem.type) {
    case 1:
      return "something";
    case 2:
      return "something else";
    default:
      return "default value";
  }
});

Without using a switch statement, you can easily accomplish what you're trying to accomplish:

const newArray = oldArray.map((elem, index, array) => {
  if (index+1 < array.length && elem < array[index+1]) { //ensure you're not at the end of the array before checking your condition
    return "something";
  } else {
    return "something else"; 
  }
});

Refs:

Post Status

Asked in February 2016
Viewed 3,071 times
Voted 14
Answered 2 times

Search




Leave an answer


Quote of the day: live life