When matching an array, check the property of the next element

Now I am viewing the array through ie

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 capture the type of the next element. I know that it is possible to use it for a loop with step i, but you need to do this inside the map. I am open to suggestions using libraries like lodash (could not find anything in the documentation).

+4
source share
2 answers

Array.prototype.mapcalls it a callback with parameters 3 :

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

This means that of course you can access the array through its index as part of the callback procedure. For example:

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

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

+7

, Array.prototype.map , , .

:

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

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

Array.prototype.map :

  • :

  • index:

  • :

switch. : case .

, , :

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

switch , :

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"; 
  }
});

:

0

Source: https://habr.com/ru/post/1627828/


All Articles