'Get next object after selected object in array

I need to create function that receives object with a boolean attribute, changes its value to false, then gets next item in array and changes its value to true. If provided object is the last item in the array, then we come back to the first item.

In other words, function should have these outcomes when invoked:

Example 1

const arr = [
  { 
   id: 1, 
   chosen: false 
  }, 
  { 
   id: 2, 
   chosen: true 
  }, 
  { 
   id: 3, 
   chosen: false 
  }, 
];

const chosenObject = arr[1];

functionToBeCreated(chosenObject); // Outcome: [{ id: 1, chosen: false }, { id: 2, chosen: false }, { id: 3, chosen: true }]

Example 2

const arr = [
  { 
   id: 1, 
   chosen: false 
  }, 
  { 
   id: 2, 
   chosen: false 
  }, 
  { 
   id: 3, 
   chosen: true 
  }, 
];

const chosenObject = arr[2];

functionToBeCreated(chosenObject); // Outcome: [{ id: 1, chosen: true }, { id: 2, chosen: false }, { id: 3, chosen: false }]

Do you have maybe any ideas how it can be archived?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source