The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task:

  • This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array.
  • The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characters and the values are the count of repeated occurrences.

Issue at Hand:

  • The problem arises when trying to reuse the arrDuplicateValues array. During the second iteration, the array appears to have a length of 0 even though it contains items.

Access the code here for testing purposes

var arrNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 0 ,4, 6, 8, 4];
var arrString = ["a", "e", "i", "o", "u", "a", "i", "u", "i"];

var arrDuplicateValues = new Array();
// First iteration: For numbers
arrNumber.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // Outputs successfully


// Second iteration: For strings
arrDuplicateValues = new Array();
arrString.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // Does not output as expected
console.log(arrDuplicateValues["i"]);

Answer №1

Using objects instead of arrays is the preferred approach in this scenario. Arrays function as lists with indexes, whereas objects offer more flexibility and customization.

Here is a practical example:

var arrNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 0 ,4, 6, 8, 4];
var arrString = ["a", "e", "i", "o", "u", "a", "i", "u", "i"];

var arrDuplicateValues = {};
// First time: Numbers only
arrNumber.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // Works fine


// Second time: With strings
arrDuplicateValues = {};
arrString.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // Does not work as expected
console.log(arrDuplicateValues["i"]);

Answer №2

arrDuplicateValues transforms into an object on the second attempt because arrays do not support string indexes. Even though you initially declared it as an Array(), it evolved into a map (key-value pair), which is why attempting to print the entire map resulted in nothing being displayed. The solution is to change the initialization to arrDuplicateValues = {}; on the second try for it to work correctly.

var arrNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 0 ,4, 6, 8, 4];
var arrString = ["a", "e", "i", "o", "u", "a", "i", "u", "i"];

var arrDuplicateValues = new Array();
// First time: Numbers only
arrNumber.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // OK

// Second time: Including strings
arrDuplicateValues = {};
arrString.forEach(x => {
  arrDuplicateValues[x] = (arrDuplicateValues[x] || 0) + 1;
});
console.log(arrDuplicateValues); // NOK
console.log(arrDuplicateValues["i"]);

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

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This ...

Is there a way to determine if a certain class link within a DIV has been clicked and then replace the DIV's click functionality?

I have multiple DIV elements like the one below on my webpage: <div class='entry'> This is a statement <a title="Search @travel" class="app-context-link" href="">@travel</a> </div> When a DIV with the class .ent ...

How can audio be efficiently streamed to the browser in small chunks using JavaScript?

I am currently working on setting up an internet radio station where I want to easily switch songs and overlay sounds. My goal is to limit the audio rate so that the feed can be adjusted before being sent out. Additionally, I would like to provide continuo ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...

What confusion do I have regarding resolving promises in Angular's state management?

Here is the state defined in appRouteConfig.js, where I am using $promise to verify userList: .state('userAccounts',{ url:'/userAccounts', controller:'UserAccount', resolve:{ registerService: "registerServ ...

Automatically assigning a FormData key/value pair upon clicking using Puppeteer in NodeJS

While working on a NodeJS project, I am using Puppeteer to fill out a form. So far, the regular type and click functions work perfectly. After clicking the "submit" button, a POST request is sent to the server with some form data. I want to add a key/value ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Update the contents of a div element with JavaScript and PHP combo

When I click on the following div, I want to replace it with a similar one from file.php. The div tag in question is: <div style="display: none;" id="extra" class="container2" xml:id="page"> <div class="title"> <h2>Stuff to check out< ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those ...

Google Maps autocomplete feature is causing the input to update only after clicking in ng-model

After fetching a Google Maps place ID from a REST API, I utilize the Google Maps API to retrieve the place object in this manner: var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'placeId': data.city }, fun ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Combining an array in PHP with a changing key

When I retrieve an array in the following format: $arr1: 0 => 'id' => 1, 'name' => 'a' 1 => 'id' => 2, 'name' => 'b' 2 => 'id' => ...

The index "is_ajax" has not been defined

I attempted to create a simple login functionality using Ajax. Following a tutorial that didn't use classes and functions in PHP, I tried restructuring the code with classes and functions. However, I encountered the error: Undefined index: is_ajax He ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...