Retrieve the succeeding object in the array following the selected object

I am seeking help in developing a function that takes an object with a boolean attribute and changes its value to false, then proceeds to the next item in an array and changes its value to true. If the provided object is the last item in the array, the function should cycle back to the first item.

To clarify, these are the desired outcomes when the function is called:

Example 1

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

const chosenObject = arr[1];

functionToBeCreated(chosenObject); // Expected 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); // Expected Outcome: [{ id: 1, chosen: true }, { id: 2, chosen: false }, { id: 3, chosen: false }]

Any suggestions on how this functionality can be achieved?

Answer №1

Examine the code for explanations.

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

// The pointer representing the current selection needs to be mutable
let chosenObject = 1;

function functionToBeCreated(chosen){

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

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

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery change event does not fire once the DIV has been rendered, while working with CakePHP

Whenever a room_id is chosen from the drop-down menu, I utilize the JS helper to automatically fill in the security_deposit and room_rate input fields. However, there seems to be an issue where selecting a room_id causes the room_rate_update jQuery change ...

Vanishing Items - Three.js CanvasRenderer

I'm in a bit of a pickle here. I can't figure out why my objects are disappearing when using the canvas renderer. Strangely enough, everything works fine with the webGL renderer. Unfortunately, I need to make sure this displays properly on mobile ...

Showing Div content from AngularJS response

Query -- I am currently using a Controller in AngularJs that performs an $http.get request and receives data as a response. The data includes an HTML DivID and corresponding classes. How can I extract this DivID from the response and transfer it to the vi ...

Combining disparate arrays with serialized name/value pairs

Is there a way to merge an unassociated array with serialized name/value pairs without manually iterating over them? //First, I select certain values from mytable var data = $('#mytable input:checked'); console.log(data); //Object[input attribu ...

I'm having trouble launching Clinic.js, any suggestions on what steps I should take next?

When starting up your application, use the following command: clinic doctor --on-port 'autocannon -m POST localhost:8000/users/register' -- node dist/main.js If you need help, check out the Clinic.js Doctor - v9.2.0 log. The clinic doctor tool ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

What is the method for determining the required or imported base path?

My package.json includes the main option to set the default file for importing like import 'my-index' from 'my-module' However, I would like to break up my-module into separate files so developers can include them individually with sta ...

Strange occurrences of radio buttons in AngularJS

When working with radio buttons, I noticed a strange behavior that I wanted to share. My goal was to have Radio Button 1 selected if the array is undefined, and Radio Button 2 selected when the array is defined. In the initial state, the array is indeed ...

Showing user input on a separate page with the help of Ajax

I could use some guidance on how to display text sent via the post method to another page. My Requirements: To enter text in a textarea, and if a checkbox is selected, automatically send any changes made in the textarea to another page where the updated ...

Ensure that the onPrepare method of the protractor is configured to wait for async HTTP requests

I have a query regarding my protractor conf.js file. The onPrepare function in it needs to include an http request that is structured like this, onPrepare: function(done) { request.get('http://pepper/sysid') .end(function(err, resp){ ...

Troubleshooting: Node.js and EJS throwing 404 Error on delete function

I am encountering an issue where I am successfully retrieving the project ID, but when the delete method is called, it results in a 404 error. The code used for this scenario is as follows: Front End <% for(var i=0; i<projects.length; i++) {%> ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

What is the best way to implement multiple store filters in VueJS?

Just dipping my toes into the world of VueJS with my very first major project. I've incorporated 2 filters in this project for my elements - one is a search bar and the other involves checkboxes. Taking a look at my code, you'll notice a computed ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

Ways to show an input box even when there are no results found

I currently have a database with 5 books, but only 3 of them have prices listed. How can I modify my code to display an input box for all books, regardless of whether they have a price in the database? I am new to coding, so I would appreciate it if you co ...

Viewing code on Ionic Serve is as quick as a blink of an eye

I am experiencing a strange issue where my code appears for just a moment after running ionic serve and then disappears. I have all the necessary components like nodejs, cordova, ionic, jdk, etc. installed on my machine. As a newcomer to ionic, I would rea ...

Discovering the clicking actions on PDF elements within an HTML environment

I am currently working on developing a web application that involves rendering various pdf objects. My main goal is to be able to detect the position of a click inside the pdf container. However, it seems like the OnClick event is not functioning as expe ...