The .slice() function in TypeScript has the ability to alter the initial array

I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code:

class ChapterOne {
    
    // Gauss Jordan Elimination
    // Notes: Only solve system of linear equation with one solution
    static gaussJordanElim( linsys : number[][] ) {
        const numOfEquation = linsys.length
        const numOfUnknown = linsys[0].length - 1
        if (numOfUnknown > numOfEquation) return 'This System of Linear Equation either have no solution or have infinite solutions'
        
        // I slice it here.
        const input = linsys.slice()
        const length = input.length
        // pointer = i, row to operate = j, column to operate = k
        for (let i = 0; i < length; i += 1) {
            if (input[i][i] === 0) return 'Mathematical Error! Cannot divide by zero'
            for (let j = 0; j < length; j += 1) {
                if (i !== j) {
                    const ratio = input[j][i] / input[i][i]
                    for (let k = 0; k < length + 1; k += 1) {
                        input[j][k] = input[j][k] - ratio * input[i][k]
                    }
                }
            }
        }
        // I Checked it here
        console.log(input)
        console.log(linsys)

        const output = input.map((row, pointer) => row[length] / row[pointer])
        return output
    }
}

In essence, I created a duplicate of the original array, made various alterations to the duplicate without affecting the original, but noticed changes in both arrays when logged. Can someone shed light on why this is happening?

The primary objective is to clone the initial array, modify the cloned version, and preserve the original intact.

Answer №1

This issue arises due to the behavior of .slice method in JavaScript which performs a shallow copy and does not duplicate nested objects. When dealing with a two-dimensional array, this behavior is to be expected.

To resolve this, you can use the following code snippet:

const input = JSON.parse(JSON.stringify(linsys))

Shallow cloning only replicates the top-level object properties and does not create copies of nested objects. Therefore, when an object contains another object, using .slice will result in maintaining a reference to the original object rather than creating a new one. This leads to unexpected changes in values.

When performing a shallow copy:

  • Objects will reflect changes made at the original location from where they were shallowly copied, as they are stored by reference (address in Heap).
  • Primitive data types will NOT reflect changes in the original location because they are directly stored in callstack (Execution Contexts).

For instance:

var a = [
    [1, 2],    // This still refers to the original reference 
    [5,7]
]

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

Retrieval of components from JSON array of objects

I have a JSON array containing objects stored on the server. How can I access the first object to print its contents? The data is in the following format: [ { "eventId": "8577", "datasetId": "34", "nodeId": "8076", "typeId": "4", "type": ...

What is the most effective approach to scan Angular 2, 4, 5 template html files before AOT compilation for optimal code quality assessment?

Recently, I stumbled upon an interesting GitHub repository called "gulp html angular validate". If you're not familiar with it, you can check it out here. However, I have doubts about whether this tool is suitable for Angular 2+ projects. Additionall ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Incorrect types being identified

What is the reason behind the callback assuming the type string | number | boolean instead of determining the exact type based on the property passed as the first argument in the carWithListener.on function? const car = { paint: "red", ...

Error: Unable to iterate over the albumlist property as it is not a function

I keep encountering the error message TypeError: this.state.albumlist.map is not a function whenever I attempt to display the retrieved data. I am unable to pinpoint the exact issue in my code that is causing this error. Can anyone assist me with troubles ...

Tips for importing a non-namespaced module TypeScript definition into my custom types

When working with my custom types, I want to utilize the GraphQLSchema from the graphql module. If I simply write: interface MyThing { schema: GraphQLSchema } It doesn't reference the actual GraphQLSchema definition from the module (it's just ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

Exciting Dynamic Text Animation in React using styled components

I came across this cool jumping text effect on https://web.dev/patterns/animation/animated-words/ and wanted to incorporate it into my app. However, when I tried implementing the component in React, I encountered some issues. I created a styled component a ...

I'm curious about the origins of the "readme" field within the artifact registry file

Within our private npm registry on Azure, we house our own npm package alongside the npmjs packages. One particular package, @typescript-eslint/parser, has caused our pipelines to fail during the npm install task due to a SyntaxError: Unexpected end of JSO ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises wh ...

Build for Node.js using TypeScript with full functionality

When compiling TypeScript for Node.js using tsc --module commonjs --target ES5 I face limitations with async/await and generators as tsc doesn't know how to handle them in ES5. To address this issue, I can compile TypeScript for Node.js with tsc - ...

Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly. Here is a snippet of my API code: .post('/type/add', function(req, res){ var type = new NewType({ type: req.body.type, subtype: req.body.subtype, }); type.save ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

Is there a way to instantiate a new object within the same for loop without replacing the ones created in previous iterations?

My current issue with this exercise is that as I convert the first nested array into an object, the iteration continues to the next nested array and ends up overwriting the object I just created. I'm wondering how I can instruct my code to stop itera ...

Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the s ...

Accessing JSON data from an external source using PHP

I need assistance with reading JSON data from PHP. Here is a snippet of the JSON I am working with: [{ "titulo": "DontAsk", "pais": "Austria", "country_iso": "AT", "direccion": "Mag. Th. Langmann Gmbh Landstrasse 4", "cp_ciudad": "A-2000 STO ...

An error is triggered when an HttpClient post does not return any data

While sending a post request from my angular application to a web api, I am encountering an issue. The response from the api is supposed to be either a 200 status or a 404 status without any data being returned. An example of some headers for the 200 respo ...