JavaScript function produces erratic outcomes due to variances in input data

Experimenting with JavaScript today led me to discover something strange when using the spread syntax and fill() function. Here is the code I used:

     let v = [...Array(9).fill([])];

        function myFunc(){
         arr = [1,5,2,3,4,6,8,9,7];
     
        arr.map((val, i)=> {
             v[i].push(val);
        });  
    }

   myFunc();

The resulting v-array looks like this:

Array(9) [ (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […] ]
​
0: Array(9) [1,5,2,3,4,6,8,9,7]
​
1: Array(9) [1,5,2,3,4,6,8,9,7]
​
2: Array(9) [1,5,2,3,4,6,8,9,7]
​
3: Array(9) [1,5,2,3,4,6,8,9,7]
​
4: Array(9) [1,5,2,3,4,6,8,9,7]
​
5: Array(9) [1,5,2,3,4,6,8,9,7]
​
6: Array(9) [1,5,2,3,4,6,8,9,7]
​
7: Array(9) [1,5,2,3,4,6,8,9,7]
​
8: Array(9) [1,5,2,3,4,6,8,9,7]
​

It appears that each sub array in v was filled sequentially with the same amount of numbers. The behavior is somewhat confusing to me. However, by simply changing the initialization line from:

 let v = [...Array(9).fill([])];

to:

let v = [[],[],[],[],[],[],[],[],[]];

Everything worked as expected.

Array(9) [ (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […] ]
​
0: Array [ 1 ]
​
1: Array [ 5 ]
​
2: Array [ 2 ]
​
3: Array [ 3 ]
​
4: Array [ 4 ]
​
5: Array [ 6 ]
​
6: Array [ 8 ]
​
7: Array [ 9 ]
​
8: Array [ 7 ]

This serves as a reminder for those who might encounter the same issue. If anyone can provide insight into this phenomenon, I would greatly appreciate it.

Answer №1

When you implement the following code:

let v = [...Array(9).fill([])];

You are populating the array with identical empty arrays.

To improve your code, you can do the following:

const EMPTY_ARRAY = [];

let v = [...Array(9).fill(EMPTY_ARRAY)];

Subsequently, when adding elements, they will all be pushed to the same array (EMPTY_ARRAY).

If you want to verify that it is indeed the same array, compare the elements within it like this:

let v = [...Array(9).fill([])];

console.log(v[0] === v[1])

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

Transferring an array of cells from MATLAB to Java using MATLAB

In my MATLAB programming project, I have a collection of cell type objects that store arrays of doubles. The structure consists of a <1xn cell> array where each cell contains an array of doubles. My goal is to export this data in a way that allows m ...

Obtain values from a two-dimensional numpy array by using another two-dimensional array as indices

I have a 2D array with the following values: >>> arr = np.array([[1,2],[3,4]]) >>> arr array([[1, 2], [3, 4]]) Additionally, I have another array with the same number of columns as the input array. Each row in this array contains ...

Experiencing a DNS error while running a JavaScript script using Node.js

const { Client, EmbedBuilder, GatewayIntentBits, Collection, Events, Partials } = require("discord.js"); require("dotenv").config(); const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits; const { User, Message, GuildMember, ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...

organize the array first based on its values and then by its keys

Let's say I am working with an array: $array => Array ( [5] => 0.33 [3] => 1 [2] => 0.33 ) After executing asort($array), the array becomes: $array => Array ( [5] => ...

The issue of AngularJS memory leaks

We're facing a memory leak issue in our AngularJS application when switching between different sections. Pinpointing the root cause has been a challenge for us. Our app includes a main controller with a sub controller nested within it. The sub contro ...

Encountered a TypeScript typing error when retrieving data from the Pinia state to populate the template

Having a type error when trying to pass data from the Pinia store to a child component's input field using TypeScript - Error message: 'Property 'storeForm' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $prop ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

How can we sort out variable numerical values within a specific range in a PHP array?

I have a function that generates an array containing numerical values that are constantly changing. The range of values is predetermined, with the highest value determined by the last digit (e.g. _1, _2, _3). Though I am unsure if using range() is the sol ...

Tips for dividing a single row retrieved from a MySQL database that has been converted with json_encode so that it can be shown in

Looking to extract data from a MySQL query result in one PHP page and transfer it to a separate page with JavaScript. Here is my attempt so far: I am aiming to retrieve specific values from the selected row in the MySQL table and populate them into #event ...

What is the best technique for evaluating different businesses' operating hours?

I am trying to compare the opening hours stored on my server with the current time. Here are the details: Start: 09.00 End: 00.30 The goal is to determine if the store is open or closed based on the current time. If the current time falls outside of t ...

Implementing Bootstrap modal functionality in PHP

I'm attempting to trigger a hidden modal from an HTML file using PHP as part of a verification process. One modal is displayed when a button is clicked, while the other is meant to be called by PHP. Below is my PHP code: $File = include("index2.html ...

The callback response in Node's exec function is behaving incorrectly

When I have a route handling a URL post request, I am running an exec on a bash command. Strangely, the console.log is working fine indicating that the bash command ends and the callback is triggered. However, for some reason, the response fails to send ...

What could be causing my MongoDB Node.js driver's $lookup aggregation query to not produce the expected results?

In my database, I have two collections: users and roles Each user has an array of roles assigned to them: { _id : 61582a79fd033339c73ee290 roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd] } The roles are defined as follows: [ { ...

Running multiple languages locally may encounter issues, however, Codepen operates smoothly without any problems

While conducting research, I came across several options for creating multilingual websites. After implementing one method (jQuery), I noticed some slowness in translation and processing the information. Additionally, it only partially worked in the normal ...

Implementing a vertical tabindex change in Material UI Dialogue table

My material UI dialogue contains a table: <Dialog open={open} onClose={handleClose} maxWidth={'xl'} aria-labelledby='scroll-dialog-title' aria-describedby='scroll-dialog-description' disa ...

Secure user verification using session variable in the Express framework with NodeJs

Is it safe to use session variables for login persistence in the backend? What are the security implications and alternatives to consider? Technology Stack: Express (NodeJs) on the backend, MaterialUI (React) on the frontend I am seeking a straightforwa ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

Cease the video playback in the modal when the modal is closed

I've attempted several solutions found on stack overflow, but none of them seem to be effective. When I replace the video tag with an iframe, some solutions work, but the video autoplays again, causing issues with the solution. <div class="ico ...