Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment.

Here is a sample array data:

const data = [ 
     { type:'yes',start:1 }, //count index starting point
     { type:'yes',start:1 },
     { type:'no',start:0 }, //skip
     { type:'no',start:0 }, //skip
     { type:'yes',start:5 }, //new index starting point
     { type:'yes',start:5 },
     { type:'no',start:0 },  //skip
     { type:'yes',start:5 }, //new index starting point
     { type:'yes',start:5 },
     { type:'no',start:0 },  //skip
     { type:'yes',start:10 },//new index starting point
     { type:'yes',start:10 },
     { type:'yes',start:10 }, 
]

If the loop is executed like this:

for(var i = 0; i < data.length ; i++){
    // code here
    console.log( **newindex** )
}

The expected output for newindex would be:

1,2,0,0,5,6,0,5,6,0,10,11,12

Appreciate any help with solving this issue. Thank you!

Answer №1

A combination of map and a loop can be utilized in this scenario

const dataxd = [ { type:'yes',start:1 }, { type:'yes',start:1 }, { type:'no',start:0 }, { type:'no',start:0 }, { type:'yes',start:5 }, { type:'yes',start:5 }, { type:'no',start:0 }, { type:'yes',start:5 }, { type:'yes',start:5 }, { type:'no',start:0 }, { type:'yes',start:10 }, { type:'yes',start:10 }, { type:'yes',start:10 }, ]
 ns=dataxd.map(o=>o.start)
 counter=1
 for (let i=0;i<ns.length;i++){
    if(ns[i]==0) {counter=1;continue}
    else if(ns[i-1]!=0 && i!=0) ns[i]= ns[i]+counter,counter++  
 }
 console.log(ns)

Answer №2

Give this code a shot. It will adjust the start index if two items are equal: The resulting sequence will be //1,2,0,0,5,6,0,5,6,0,10,11,12

const data = [ 
   { type:'yes',start:1 }, //set starting point
   { type:'yes',start:1 },
   { type:'no',start:0 }, //skip
   { type:'no',start:0 }, //skip
   { type:'yes',start:5 }, //new starting point
   { type:'yes',start:5 },
   { type:'no',start:0 },  //skip
   { type:'yes',start:5 }, //new starting point
   { type:'yes',start:5 },
   { type:'no',start:0 },  //skip
   { type:'yes',start:10 },//new starting point
   { type:'yes',start:10 },
   { type:'yes',start:10 }, 
];

let increment = 0;
for(var i = 0; i < data.length -1 ; i++) {
    console.log(data[i].start + increment);
    if (data[i].start !== 0 && data[i].start === data[i+1].start) {
      increment++;
    } else {
      increment = 0;
    }
    if(i === data.length - 2) {console.log(data[data.length-1].start + increment);}
}

Answer №3

const data = [ 
   { type:'yes',start:1 }, //initial index point
   { type:'yes',start:1 },
   { type:'no',start:0 }, //ignore
   { type:'no',start:0 }, //ignore
   { type:'yes',start:5 }, //new starting index
   { type:'yes',start:5 },
   { type:'no',start:0 },  //ignore
   { type:'yes',start:5 }, //new starting index
   { type:'yes',start:5 },
   { type:'no',start:0 },  //ignore
   { type:'yes',start:10 },//new starting index
   { type:'yes',start:10 },
   { type:'yes',start:10 }, 
];

let index = 0;
let counter = 0;

let result = data.map((obj) => {
  if (obj['start'] !== 0) { // If start value is 0, move to else block
    if (index !== +obj['start']) { // If start value changes
      index = +obj['start']; // Store new start value in index
      counter = +obj['start']; // Store new start value in counter
      return obj; // return for the first time
    }
    counter += 1; // After the first time : Increment saved start value by 1
    obj['start'] = counter; // Update start value
    return obj; // Return the updated object
  } else {
    index = 0; // Reset index to 0
    return obj; // Return the same original object
  }
});

console.log(result);

Answer №4

To ensure a smooth transition between index starting points, it is recommended to utilize an external control variable. Here's a practical example to illustrate this concept:

const data = [ 
 { type:'yes',start:1 }, //initializing with index 1
 { type:'yes',start:1 },
 { type:'no',start:0 }, //skipping
 { type:'no',start:0 }, //skipping
 { type:'yes',start:5 }, //shifting to index 5
 { type:'yes',start:5 },
 { type:'no',start:0 },  //skipping
 { type:'yes',start:5 }, //continuing at index 5
 { type:'yes',start:5 },
 { type:'no',start:0 },  //skipping
 { type:'yes',start:10 },//moving to index 10
 { type:'yes',start:10 },
 { type:'yes',start:10 }, 
]

let startingPoint = 0

for(var i = 0; i < data.length ; i++){
    if (data[i].start === 0 || startingPoint === 0) {
      startingPoint = data[i].start
    } else {
      startingPoint += 1
      data[i].start = startingPoint
    }
    console.log(data[i].start)
}

//Expected output: 1,2,0,0,5,6,0,5,6,0,10,11,12,13

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

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Incorrect measurement of text size

My attempt at creating a basic font size changer was working perfectly until I integrated it with the bootstrap framework. Strangely, when I try to increase the font size, it actually decreases instead. var baseFontSize; (function () { "use strict"; ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Use npx to reverse the update from React version 18 to version 17

Is there a way to downgrade a project created using "npx create-react-app . --template typescript"? I've tried manually changing dependencies and then running "npm install" as suggested online, but I always encounter errors. How can I adjust the depen ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

"Troubleshooting a blank page issue in Angular UI Router caused by query string

I've been struggling with an issue related to query string parameters for quite some time. When I navigate to /, everything works perfectly fine. However, if I try something like /?anything, it simply doesn't work. These are the configurations in ...

Having trouble with ui-sref functionality within a Bootstrap dropdown menu

In the header.html file, I have the following angular code: <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> &l ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

Having trouble establishing a connection to the FTP server through the "ftp" package provided by npm

Attempting to establish a connection to a Secured FTP server using the "ftp" package. When connecting to an unsecured server, everything functions as expected with all events firing and content being displayed. However, upon trying to connect to a server ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

Can a direct link to a Redis server be established through a web browser?

Can a connection be established with a redis server directly from the browser? In node, you can create a TCP connection using var client = net.connect(port, host);. I'm curious if it's possible to achieve the same in the browser either through Br ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: This is the TypeScript file for my components: And these are the response models: I am currently facing difficulties with displaying asynchronously fetched data in my component's TypeScript file using an Observabl ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

When using the require() function in Node.js, the period "." is not being recognized as part of the command and

I recently encountered a problem while working on my project and reorganizing my files. I noticed that the "." in my requires are not being parsed correctly. Upon running my program, an error message is displayed: Error: Module './src/map/createMa ...

Issue with extended waiting times in polling

I am currently working on a chatroom using the long poll method. However, I'm facing an issue where every time a long poll occurs and I refresh the page in Chrome or try to send another async request, everything times out. This means I can't load ...