Only the first iteration of a for loop is updating the array

This particular script is designed to work with an array of objects that are structured in the following way: {html:whatever number:number value}.

function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}

When provided with [{html:null,number:1},{html:null,number:1}], the expected output for the console log of Nums should have been [1,1] on the second iteration. However, it actually logs [1] on both the first and second iterations. This unexpected result raises the question: What might be causing this discrepancy?

Answer №1

It is important to remember to declare the variable num outside of the loop in order to prevent creating a new empty array for each iteration.

Also, there is no requirement to use an additional variable for data.

function Organization(data){
    var numbers = [];
    for (var i = 0; i < data.length; i++){
        numbers.push(data[i].number);
    }
    console.log(numbers);
}

Answer №2

Or in a more concise way:

let displayData = data => console.log(data.map(item => item.number));

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

Initiate an animation in Wordpress once the entire page has finished loading

Recently, I incorporated some "raw html" elements with animations into my WordPress site. However, the issue I'm facing is that these animations kick off as soon as the page loads, without waiting for the preloader to complete and display the actual c ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

Handling overlapping elements with pointer events

Suppose I have two overlapping divs, along with the following jQuery code snippet: $( "#div1" ).click(function() { console.log('click on div1'); }); $( "#div2" ).mousemove(function() { console.log('mousemove on div2'); }); From w ...

Exploring Event Propagation in AngularJS

Currently, I am working on developing a web application using angularjs for the first time. A key feature that I aim to introduce is the ability for users to create a div in the main window upon clicking on an image in the menu. To achieve this functional ...

How to make Jquery skip over elements with a particular data attribute

I am looking to select all elements that are labeled with the 'tag' class. Once these items have been selected, I would like to remove any items from the list that contain the attribute 'data-tag-cat'. var tags = $('.tag'); c ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Error in AWS Lambda: JSON parsing error due to unexpected token 't' at position 6

I'm currently working on a basic lambda function that utilizes a post request to insert data into DynamoDB. However, every time I deploy the lambda function and test it using Postman, I keep encountering a 502 Bad Gateway error. To troubleshoot this ...

Error encountered in jQuery validation script due to incorrect data type

Looking to experiment with the jQuery validate plugin in an MVC application by trying a simple example. Here is a JS module with a method: ValidateRestriction: function (element) { var inputs = $('form').validator(); inputs.data("validat ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...

Using Perl arrays within a PostgreSQL INSERT query

There seems to be a logical issue within my code. In my MongoDB database, I have fields for template, value, row, and column. For example, if $record->{template} is T1, $record->{column} is 1, and $record->{row} contains dates in the format "d.m.Y ...

Replacing characters in a document using positions derived from a separate file

I am faced with a challenge involving files that contain six lines each. An example snippet is provided below: cat test.fa >chain A MIRLGAPQTLVLLTLLVAAVLRCQGQDVQEAGSCVQDGQRYNDKDVWKPEPCRICVCDTGTVLCDDIICEDVKDCLSPEIPFGECCPICPTDLATASGQPGPKGQKGEPGDIKDIVGPKGP ...

What is the best way to extract specific values from a JSON array of objects using JavaScript?

I am facing some challenges in displaying values from the AJAX objects. My goal is to populate a select box with names using AJAX, but I seem to have made an error somewhere in my code. Can someone please assist me in identifying and correcting the mistake ...

Is there a way for me to make my image source dynamically switch between 3-4 different images when hovered over?

I'm in the midst of a college project where I'm designing a clothing website. What I'm aiming for is to have the product image on the main feed change between 3-4 images of the same product with a quick transition when a user hovers over it. ...

Using the Promise function with callback to map the JSON payload object into an object

I received a JSON payload with the following structure: { "name": "Reports", "subject": "Monthly Reports", "attachments":[ { "attachment":{ "name": "Month1.pdf", "type": "application/pdf", "path": "h ...

Anchor point located within a scrollable div with a fixed position

A unique challenge has presented itself with a div called #results that appears when words are entered into a text box, triggering relevant results. This particular div is fixed and scrollable, with pagination located at the bottom of the scroll. The iss ...

Comparing unique values between objects in JavaScript with varying keys

I'm facing a peculiar issue that I can't seem to solve. I have two variables named nft and web3.givenProvider. Both of them have an address value of "0x0000000000000", but they are stored under different keys - nft is under .seller and ...

Making adjustments to text in HTML without altering the CSS or styling is proving to be challenging

When attempting to modify a h1 tag without changing the CSS, I encountered an issue. Below is the string with and without the JavaScript: String without JavaScript: https://i.sstatic.net/JWOmq.png String with JavaScript: https://i.sstatic.net/RNMur.png ...

Error: Cannot run yarn dev because node_modules/node/bin/node is missing

While running Next.js on my Windows machine, I am noticing that the file path is displaying as if it were a Linux path. I have already configured the node file path in the environment variable, but I'm still encountering the following error: yarn run ...

Tips for representing entire months as object keys using numerical values

Currently, I find myself a bit puzzled as to why my code is not functioning as expected, and I am hopeful that you all could assist me in solving this issue. The data structure I am working with consists of years and corresponding months. chosenMonths = { ...