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

how can I display the JSON description based on the corresponding ID using Ionic 3

I have a JSON file containing: [{ "id": "1", "title": "Abba Father (1)", "description": "Abba Abba Father." }, { "id": "2", "title": "Abba Father, Let me be (2)", "description": "Abba Father, Let me be (2) we are the clay." }, { ...

JQuery is facing difficulty in animating a div following the completion of a "forwards" css animation

Check out this example: http://jsfiddle.net/nxsv5dgw/ A div appears on the stage and a CSS animation is applied to it. However, when attempting to use JQuery to animate the same properties that were animated by CSS, it seems to no longer work properly. ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

Obtain the HTML of a Vue component and transmit it using an ajax POST request

I need to send an email with an HTML body using only ajax since I don't have access to the server code. Fortunately, the server has an API for sending emails. Currently, I have a dynamically rendered component called invoiceEmail. sendEmail () { ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Ways to parse a JSON array using Javascript in order to retrieve a specific value if it is present

Below is the JSON code stored in an array: { "kind": "urlshortener#url", "id": "http://goo.gl/2FIrtF", "longUrl": "http://hike.com/?utm_source=facebook", "status": "OK", "created": "2015-09-22T13:45:53.645+00:00", "analytics": { "allTime": { ...

Looking to extract the expiration date from an x509 certificate?

I am currently engaged in a project that involves retrieving and displaying certificate information from an Azure integration account using Angular/Typescript. One of the requirements is to show the decoded public certificate to users to extract important ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Reveal the class to the global scope in TypeScript

ClassExample.ts: export class ClassExample{ constructor(){} } index.html: <script src="ClassExample.js"></<script> // compiled to es5 <script> var classExample = new ClassExample(); //ClassExample is not defined < ...

Angular2's asynchronous data binding is still lagging even after the data has been successfully loaded

I have integrated Firebase with Angular2 to retrieve an object. import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseObjectObservable } from 'angularfire2'; import { ActivatedRoute, Params } from '@angu ...

As a result of the Chrome 53 bug, the Yahoo Weather API encountered an insecure certificate causing the jQuery AJAX request to fail

For the past year, I've relied on the Yahoo Weather API to provide me with weather updates. I've been utilizing the following link to access the data: https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (SELE ...

Prevent users from entering past dates in the date input field

In my project, I have decided to use input type date instead of datepicker. Is there a way to prevent users from selecting back dates in input type date without using datepicker? If you have any suggestions, please let me know. Thank you! ...

Is there a way to create an infinite fade in/out effect for this?

Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

The Vue EventBus does not support passing object attributes

Looking for assistance with integrating two Vue single page components. The 'Searchbar' component features a dialog box where users input data. This data is required in the 'ResultList' component for further processing. To achieve this ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

The Vue component seems to be missing the definition of $v for Vuelidate

I've been struggling to resolve this issue. The error message I am encountering pertains to a Vue component that is utilizing the Vuelidate library for form validation. Do you have any insights on what might be causing this error? Uncaught TypeError: ...

Ajax causing unreliable posts

I am facing an issue with sending and receiving data in my mobile application. I currently use the jquery $.post function, but it seems to be quite unreliable. Issue: Occasionally, about 1 out of 10 times, the POST request is sent successfully, but the ca ...

Incorporate the module into both the parent and child class

In my coding project, I have a situation where both a parent class and a child class are importing the same lodash library. This raises the question: will the final bundled JavaScript file contain duplicate lodash code? //Parent Class import Component fro ...