Persisting the tally of iterations in an array

When working in Javascript, I have a simple for loop that increments based on a variable num, which can be any input number:

const sequenceArr = [];

  for (let i = 0; i <= num; i++) {
    const addedSum = i + i;

    sequenceArr.push({ i, addedSum });
  }

For example, if num is set to 1000, an array of objects up to 1000 will be generated where each object looks like this:

[{1, 2}, {2, 4}, {3, 6} ... {1000, 2000} ]
. If we need to extend the count to 2000, currently the for loop starts over from 0 and repeats the same operations on numbers it has already encountered. This approach seems inefficient. How can I continue the count from, say, 1001 (or the last number in sequenceArr) instead of starting fresh from 0 and counting all the way up to 2000? Would sending data to a backend and importing a JSON file help with this situation? How could I implement such a solution?

This question relates to a small side project where I am counting up to a certain number so I can perform the addedSum operation on i. Upon further inspection, it is clear that the sequenceArr remains constant, so there's no need to recalculate the same numbers repeatedly. Instead, existing numbers should be used if num is less than the length of our array, while new numbers should only be generated when necessary.

In order to update the sequence with any new continuations of the count, these additional numbers would need to be pushed or updated in the sequenceArr.

Answer №1

To add objects to an array based on the given items, you can create a function that iterates through the array and adds objects accordingly.

function addValuesToArray(array, num) {
    for (let i = array.length ? array[array.length - 1].i + 1 : 0; i <= num; i++) {
        const addedValue = i + i;
        array.push({ i, addedValue });
    }
}
  
const valuesArray = [];

addValuesToArray(valuesArray, 3);
console.log(valuesArray);

addValuesToArray(valuesArray, 5);
console.log(valuesArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Just made a small tweak in your code.

let seriesArr = []; 

function getOutput(arr, num) {
  let length = arr.length;
    for ( length ? arr[length - 1].length + 1 : 0; length <= num; length++) {
        let sumAdded = length + length;
        arr.push({ length, sumAdded });
    }
}
  

getOutput(seriesArr, 3);
console.log(seriesArr);

getOutput(seriesArr, 5);
console.log(seriesArr);

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

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

Swapping the image in AngularJS with its corresponding alt text

My image code looks like this: console.log( $scope.image ); // <img alt="hello" class="form" src="demo.jpg"> I am trying to extract just the text of alt: console.log( $scope.image ); // hello I came across a solution for jQuery here, but I need t ...

The NodeJS program fails to authenticate the Google Calendar API integration, resulting in an undefined response even when valid credentials and tokens are provided

I am seeking assistance with my Google Calendar API integration in NodeJS. I am encountering an error message indicating that the daily limit for unauthenticated use has been exceeded, requiring signup for continued usage. Despite researching this issue on ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

The checkbox is not updating as anticipated

I'm currently developing a basic widget that allows the user to change the value of either the check box OR the entire div by selecting them. Below is the code I have implemented: $(document).ready(function() { $(document).on("click", ".inputChec ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...

What is the process for creating a post using thymeleaf with spring 4 MVC that pulls data from a table?

I have a DataGrid located on the page reg_customers.html <tr th:each="listing : ${list}"> <td th:text="${listing.id}">1</td> <td th:text="${listing.ci}">1</td> <td th:text="${listing.division}">1</td& ...

Guide to showing the username on the page post-login

My MongoDB database is filled with user information. I'm looking to create a feature on the webpage that displays "Logged in as username here" at the top once users log in. My CSS skills are strong, but when it comes to JavaScript, I'm struggling ...

Is there a point at which embedding external JavaScript scripts becomes excessive?

Our main layout page contains some external scripts that are loaded after the page has fully loaded via ajax. Unfortunately, some of these scripts are quite slow as they are opening a socket.io connection, resulting in a delay in the overall page load time ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

Adding functions to the prototype of a function in JavaScript

Is there a more concise way to simplify this code snippet? var controller = function(){ /*--- constructor ---*/ }; controller.prototype.function1 = function(){ //Prototype method1 } controller.prototype.function2 = function(){ //Prototyp ...

Confirm if a value is present in every object within an array of objects and return true

Seeking to integrate a likes system in my React application, I require insight into the posts liked by the currentLoggedIn user. This will enable me to display an icon for disliking and liking accordingly. My initial approach involves creating a small fun ...

Showing the date formatted for timezone as Coordinated Universal Time

In my user interface, I am attempting to display a date in a specific timezone. For this demonstration, I will be using Americas/New_York as the timezone. Here is my approach: $scope.getStartTime = function(){ var date = new Date(); re ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

ngFor displaying items in a stacked layout within a flexible carousel

Incorporating Angular 11 along with the https://www.npmjs.com/package/angular-responsive-carousel responsive carousel has been a part of my project. The carousel is filled with mat-cards through an array. However, upon initially loading the page, all the c ...

Clearing a textarea in jQuery

I'm experiencing an issue that I can't seem to resolve on my own. Any assistance would be greatly appreciated. My function designed to clear a textbox upon click doesn't seem to be working correctly: $(function() { $('textarea#co ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...