3

Есть массив элементов

const arrsy =   [
  {
    background: 'blue'
  },
  {
    background: 'lightblue'
  },
  {
     background: 'red'
  },
  {
    background: 'lightpink'
  },
]

нужно написать функцию, которая возвращает два последующих элемента. Если их нет, то начинаем сначала.

Например:

Выбираем нулевой элемент - возвращается первый и второй. Выбираем второй - возвращается третий и нулевой (так как четвертого уже нет).

2 ответа 2

6

const arrsy = [ 
  {
    background: 'blue'
  },
  {
    background: 'lightblue'
  },
  {
     background: 'red'
  },
  {
    background: 'lightpink'
  },
];

function nextTwo(i) {
  return [
    arrsy[i = (i + 1) % arrsy.length],
    arrsy[i = (i + 1) % arrsy.length]
  ];
}

console.log(nextTwo(2));

1

Думаю один из вариантов, как-то так:

const arr = [
  {
    background: "blue"
  },
  {
    background: "lightblue"
  },
  {
    background: "red"
  },
  {
    background: "lightpink"
  }
];

function getNext(elem, arr) {
  const result = [];
  const findedIndex = arr.findIndex(
    item => item.background === elem.background
  );
  let nextIndex = findedIndex;
  for (let counter = 1; counter <= 2; counter++) {
    nextIndex += 1;
    if (nextIndex === arr.length) {
        nextIndex = 0;
    }
    result.push(arr[nextIndex]);
  }
  return result;
}

console.log(
    getNext({ background: "red" }, arr)
);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.