Use a loop to assign numbers to elements in an array based on a specific condition using JavaScript

Hello, I'm in the process of creating a looping pattern based on the conditions of the array object key. If the 'o' contains 't', the index will start from the 'n' starting point in the object, otherwise, the numbering will continue from the main counter.

Here is the data array:

 let data = [
  {o:[],n:1}, // An empty 'o' could be our main counter, which can also be dynamic or any number to start
  {o:[],n:1},
  {o:['t'],n:1}, // 't' present, so start numbering from n
  {o:['t'],n:1}, 
  {o:[],n:1}, // continue the numbering from the main counter
  {o:[],n:1},
  {o:['t'],n:1},
  {o:[],n:1},
  {o:[],n:1},
  {o:['t'],n:5},
  {o:['t'],n:5},
  {o:['t'],n:5}, 
  {o:[],n:1}, 
]

When I execute this code:

 recount(data){
   for (var i = 0; i < data.length; i++) {
     // Code implementation here 
     // Note that new values can also modify data[i].n
     console.log(**numbering**)
   }
 }

Expected output:

//numbering
//1,2,1,2,3,4,1,5,6,5,6,7,7

Thank you for your assistance!

Answer №1

This is a simple loop with a twist - it requires two counters:

  • The first counter increments every time an item in o does not contain "t".
  • The second counter acts as an offset to be added to n when an item in o contains "t". It starts at zero.
    • It increases by one for each consecutive item that meets the condition.
    • It resets to zero when no more items matching the condition are encountered.

In ES5, the code would look like this:

var data = [
  {o:[],n:1}, 
  {o:[],n:1},
  {o:['t'],n:1}, 
  {o:['t'],n:1}, 
  {o:[],n:1}, 
  {o:[],n:1},
  {o:['t'],n:1},
  {o:[],n:1},
  {o:[],n:1},
  {o:['t'],n:5},
  {o:['t'],n:5},
  {o:['t'],n:5}, 
  {o:[],n:1}, 
]

function recount(data) {
  var counter = 1;
  var offsetT = 0;

  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    if (item.o.indexOf("t") != -1) {
      item.n = item.n + offsetT++;
    } else {
      offsetT = 0;
      item.n = counter++;
    }
    console.log(item.n);
  }
}

recount(data);
console.log(data);

For completeness, here is an ES6 version of the code:

var data = [
  {o:[],n:1}, 
  {o:[],n:1},
  {o:['t'],n:1}, 
  {o:['t'],n:1}, 
  {o:[],n:1}, 
  {o:[],n:1},
  {o:['t'],n:1},
  {o:[],n:1},
  {o:[],n:1},
  {o:['t'],n:5},
  {o:['t'],n:5},
  {o:['t'],n:5}, 
  {o:[],n:1}, 
]

function recount(data) {
  let counter = 1; 
  let offsetT = 0; 

  for (let item of data) { 
    if (item.o.includes("t")) { 
      item.n = item.n + offsetT++;
    } else {
      offsetT = 0;
      item.n = counter++;
    }
    console.log(item.n);
  }
}

recount(data);
console.log(data);

Answer №2

If you require assistance in comprehending this algorithm, please feel free to reach out. I am here to explain any aspects that may be unclear to you.

let data = [
    { o: [], n: 1 }, //empty o could serve as our main counter, which may be dynamic or set to any initial value
    { o: [], n: 1 },
    { o: ["t"], n: 1 }, //t represents the starting number for n
    { o: ["t"], n: 1 },
    { o: [], n: 1 }, // continues the count of the main counter from last entry
    { o: [], n: 1 },
    { o: ["t"], n: 1 },
    { o: [], n: 1 },
    { o: [], n: 1 },
    { o: ["t"], n: 5 },
    { o: ["t"], n: 5 },
    { o: ["t"], n: 5 },
    { o: [], n: 1 },
  ];
  
  let numbering = 1;
  let secNumbering;
  let previous = false;
  
  function recount(data) {
    for (var i = 0; i < data.length; i++) {
      if (data[i].o.includes("t")) {
        if (previous) {
          secNumbering += 1;
          console.log(secNumbering);
          previous = true;
        } else {
          secNumbering = data[i].n;
          console.log(secNumbering);
          previous = true;
        }
      } else {
        console.log(numbering);
        numbering += 1;
        previous = false;
      }
    }
  }
  
  recount(data);
  

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 do RxJS collection keys compare?

Is there a more efficient way to compare two arrays in RxJS? Let's say we have two separate arrays of objects. For example: A1: [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: & ...

Exploring typeahead functionality with JSON and arrays structure

I'm facing an issue where I need to generate a json file from an sql query and utilize it with twitter typeahead. However, the current json format is not fitting the requirements for typeahead. The expected json format should look like this; [' ...

What exactly is the functionality of the jQuery.on() method?

I am curious about the functionality of this function and how it operates. Does it follow these steps: Identify element(s) using their selectors Assign event-handlers to them Execute a setInterval on that selector, consistently delegating and then undeleg ...

Shift a div out of view (using margin: 0px auto)

How can I achieve a sliding effect for two horizontally centered divs, #box1 and #box2, when a button with the class .class is clicked? The desired animation involves moving #box1 to the left and off the screen, while #box2 slides into view from the right. ...

A guide on extracting data from a JSON list of lists in SQL Server

When parsing data from an API in a SQL Server database that is returned in the JSON format provided below, there arises a challenge due to the structure of nested lists within lists: declare @json nvarchar(4000) = N'{ "List":{ " ...

Unable to display a custom image as a check mark on a checkbox

I tried to add some custom CSS to style the images on my checkmark boxes. The goal was to display an image with a checkmark when clicked, but unfortunately, it's not working as expected during testing. For this task, I utilized CSS and HTML from a he ...

Utilizing Redux actions in React components

As I was delving into React and Redux concepts, I decided to create a simple component to gain a better understanding. Now, I am attempting to divide the Redux logic into a separate component, resulting in a total of two components. However, upon compili ...

Python: Introduction to basic array manipulation techniques using Numpy

I have a query that may seem simple, but I'm struggling to find the solution: My data is stored in a long 1D numpy array like: [1,2,3,4,5,6,7,8,9,10,11,12, ... ,n1,n2,n3] This array represents the x y z positions of points, such as [x0,y0,z0,x1,y1, ...

Troubleshooting: React Testing Library Issue with Updating Material UI DatePicker Input Content

I'm attempting to update the value of the Material UI Datepicker Input using React Testing Library. Unfortunately, I have not been successful with the fireEvent.change() method. import React from "react"; import { render, screen, waitFor, fi ...

Limit the API call to only respond to requests from the localhost

I'm currently working on a website that uses API calls within the same node project. I would like to restrict most of these API calls to only be accessible by the localhost website. Is there a way to achieve this without implementing OAuth and simply ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

Incorporate seamless integration by using the npm install command

I am currently facing an issue where I need to identify and remove unused dependencies from my package.json file every time I run npm install for my app. Is there a method to automatically include the npm package https://www.npmjs.com/package during the n ...

Dynamic text input and selection menu with AJAX (PHP and JavaScript)

As a student who is new to Javascript and PHP, I am trying to create a login page for my website that can verify user input in the database using AJAX. For example, when a user enters their username and password, the system should automatically check if t ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

Is it possible to use `this` when setting a default value in TypeScript?

Does the usage of this in the parameter list of a method in TypeScript fall within the scope? Take a look at the code snippet below: class Foo { constructor(public name) {} bar(str: string = this.name) { console.log(str); } } let f = new Foo("Yo ...

Managing null values in RxJS map function

I'm facing a scenario where my Angular service retrieves values from an HTTP GET request and maps them to an Observable object of a specific type. Sometimes, one of the properties has a string value, while other times it's null, which I want to d ...

Guide: Creating an AngularJS directive for displaying a jQuery dialog that triggers submission on pressing the Enter button

Looking to create a similar functionality to the jQuery modal form Dialog in my AngularJS app to collect the username from the user. I've tried using the twitter-bootstrap modal and AngularUI dialog, but both are lacking in two key areas: Auto-focu ...

Is it possible to have code highlighting and intellisense features while typing within backticks in Visual Studio Code?

I am looking for a way to enable code highlighting and IntelliSense within backticks (``) in a .ts file in Visual Code. For example: let html =`<div><span>Hello</span></div>`; If you have experience with this feature in Atom or ar ...