Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading