[SOLVED] Get next object after selected object in array

Issue

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?

Solution

See explanations thoughtout the code.

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

// This is your chosen pointer. It has to change, so it is not a constant
let chosenObject = 1;

function functionToBeCreated(chosen){

  // Set the currently chosen property to false
  arr[chosen].chosen = false
  
  // Determine the next object.
  // This is the remainder of the division by the length of the array
  // this is a zero-based index.
  let next = (chosen + 1) % arr.length
  
  // Set the "next" chosen property to true
  arr[next].chosen = true
  
  // Update your pointer
  chosenObject = next
};

// 1st call
functionToBeCreated(chosenObject)
console.log(arr)

// 2nd call
functionToBeCreated(chosenObject)
console.log(arr)

// 3rd call
functionToBeCreated(chosenObject)
console.log(arr)

// 4th call
functionToBeCreated(chosenObject)
console.log(arr)

Answered By – Louys Patrice Bessette

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.