The discrepancy in the outcomes is puzzling to me. Javascript

let arrays = [ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(arrays);

for(i = 0; i < arrays.length; i++){
    arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays); //[ [ ' ', ' ', '-' ], [ ' ', '-', ' ' ], [ '-', ' ', ' ' ] ]

This is the desired outcome.

The following code produces a different result.

let input = 6;

const diameter = input; //6
const centralValue = Math.ceil(diameter / 2); //3

const reverseArray = (array) => {return array.slice(0).reverse();} //reverses the array
// const makeUpperLeftArrays = function(centralValue){
//}

let createEmptyArray = (number) => {return new Array(number).fill(' ')} //creates an empty array

let emptyArray = createEmptyArray(centralValue);

let addEmptyArrays = function(array){
    let addedEmptyArrays = [];
    for(i = 1; i <= centralValue; i++){
        addedEmptyArrays.push(array)
    }
    return addedEmptyArrays;
}
let addedEmptyArrays = addEmptyArrays(emptyArray);


let arrays = addedEmptyArrays
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(arrays);

for(i = 0; i < arrays.length; i++){
    arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays);

I am in need of assistance...

I have attempted debugging, removing it from the function, changing the name, but to no avail.

Answer №1

Passing arrays by reference

[...array] solves the issue

let input = 6;

const diameter = input; //6
const middleValue = Math.ceil(diameter / 2); //3

const reverseArr = (arr) => arr.slice(0).reverse(); //reverses an array


let createEmptyArr = (num) => Array(num).fill(' '); //creates empty array

let emptyArr = createEmptyArr(middleValue);

let addEmptyArrs = function(arr){
    let addedEmptyArrs = [];
    for(i = 1; i <= middleValue; i++){
        addedEmptyArrs.push([...arr])
    }
    return addedEmptyArrs;
}
let addedEmptyArrs = addEmptyArrs(emptyArr);


let allArrays = addedEmptyArrs
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(allArrays);

for(i = 0; i < allArrays.length; i++){
    allArrays[i][(allArrays.length - 1) - i] = '-'
}
console.log(allArrays);

Answer №2

When examining this line,

The element at the end of the array is pushed into addedEmptyArrays

you keep adding the same reference to the array, causing any changes made here to affect all instances (since they are the same).

arrays[i][(arrays.length - 1) - i] = '-'

To resolve this issue, create a new instance each time you push to the array. Simply replace the highlighted line with:

New instances are created every time elements are added to the empty arrays.

This adjustment should produce the desired outcome and enable you to streamline your code by generating new instances during the pushing process.

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

The GAS web application is experiencing issues with sorting dates correctly on the Javascript table

I have a food consumption log in a table that I need to sort. When I attempt to sort by the date column, I notice an issue with how it groups numbers together. For example, the sorting places all dates starting with 10 between 1 and 2, then all dates star ...

An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for. The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all C ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Expanding the Girth of a Curved Trajectory in Three.js

I successfully crafted a racetrack-inspired curve using three.js by employing the given code snippet: var path = new THREE.Path(); path.moveTo(150,50); path.lineTo(150,150); path.quadraticCurveTo(150,175,100,175); path.quadraticCurveTo(50 ...

Loop through an array of JSON objects using jQuery

I am working with CodeIgniter and I have a JSON array in my Controller file that was obtained by calling various APIs: { "Specialities": [{ "SpecialityID": 1, "SpecialityName": "Eye Doctor" },{ "SpecialityID": 2, "S ...

Choose the option in real-time with Jquery

I'm currently developing a dynamic HTML for Select Option as seen below: item += "<td class='ddl' style='width:40%;'>"; item += "<select>" item += " <option id='list' name='selector' value=" + se ...

Jquery solution for toggling multiple Divs individually

I'm currently working on a small application that has both a sidebar menu and a header menu. My goal is to have all items in these menus toggle the visibility of content in one main window or page. When a button is clicked, I want it to show the corre ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

Programming the action of unfolding one window while simultaneously closing all others

I am facing an issue where the foldout function is working perfectly, but I need the second function to run first in order to close all other elements. Unfortunately, I can't seem to figure out what the problem is. Any help would be greatly appreciate ...

What strategies can I implement to combine postcss-bem with css-modules or postcss-js within a React component?

I am currently exploring the use of postcss-bem for generating CSS files in BEM style. I'm curious if there are other packages like CSS-Modules or Postcss-JS that could allow me to achieve something similar to the code snippet below: const ReactC ...

Ways to identify the moment jQuery datatable is initialized and populated with information

I am currently using the most recent version of jQuery datatables. I'm curious if there is a callback function available that triggers right after the data has been loaded and displayed in the table? While experimenting with a datatable in IE8, I hav ...

Performing create, read, update, and delete operations in AngularJS using a

Everything seems to be working fine with the CRUD operations in AngularJS. When I click on the submit button, the values are successfully submitted to the database. However, the changes are not immediately reflected on the view. I either need a separate bu ...

Compiling modal window content in AngularJS can lead to the creation of controllers that are left disconnected

I implemented a modal window triggered by fancybox in my project. Once the modal is displayed, fancybox triggers a "modalShown" event that is listened for by AppController. In this listener, $compile is called on the modal content to create the ModalContro ...

Can you explain the meaning of the code snippet i = (i + 1 == count) ? 0 : i + 1;?

I recently utilized this particular line of code in my jQuery plugin, but I find myself struggling to fully grasp its functionality. Below is a snippet of the plugin's code: Could someone provide me with an explanation? (function ($) { $.simpleS ...

When the Y-scroll reaches 100vh, add a class

Currently, I'm tackling a reactjs project and have been pondering how to convert ScrollY px values to something like vh. state = { isTop: true, }; componentDidMount() { document.addEventListener('scroll', () => { const isTop = w ...

Error: The texture is not rendering on the object in Forge Three.js

I am struggling to showcase a textured plane using Three.js within the context of Forge RCDB. Initially, I was able to render the plane; however, it appeared completely black instead of being textured... After making some adjustments, now nothing is showin ...

Exploring the possibilities of integrating CSS and JavaScript in Node.js with Express

Here is the folder structure I am working with: lifecoding |login2 |index.html |css style.css |js index.js I have all the necessary modules installed for express to work properly. However, when I try to set the static path as shown below, it keeps ...

Is there a way to determine if every number in one array is the square of a number in another array?

Define a function comp(a, b) (also called compSame(a, b) in Clojure) that determines whether two arrays a and b have the same elements with the same multiplicities. In this case, "same" means that every element in array b is the square of an element in arr ...

Upon clicking the button, the system triggers an update to the database

I am currently working on an interface that involves buttons for updating a database. For example, I have a variable named "Estado" which is initially set as "emAvaliacao". When the button "Aceite" is clicked, the value of "Estado" changes to "Aceite". Th ...

What factors determine how a React component should be re-rendered based on a specific file?

I am facing a challenge with a file that stores an array of objects. There is a component responsible for fetching data from this file and rendering the list. The issue arises when the file gets updated externally, as I need the component to reflect these ...