The slice() method in arrays provides a reference to the elements rather than copying

In my file, I am exporting an object in the following manner:

export const LINECHART2_DATA = {
    series: [{
        data: [],
        name: 'HR',
    },
    { 
        etc...
    }]
}

The way I import it is like this:

import { LINECHART2_DATA } from '../chart-options/options';

I have a method that looks like this:

prepareLineChartDataContainer(bed: BedDetails) {
//Clear data to prepare for new bed
if (bed.seriesContainer == null) {
  bed.seriesContainer = LINECHART2_DATA.series.slice();
} else {
  bed.seriesContainer.forEach(series => {
    series.data.length = 0;
  });
}
//Add data to seriesContainer
this.vitalSigns.forEach(vs => {
  bed.timeWindows.forEach(tw => {
    bed.seriesContainer.find(series => series.name == vs).data.push(tw['avg' + vs]);
  });
});
}

As shown above, I am using the slice() method on the series array from LINECHART2_DATA and then adding some data to it. When a new bed is passed into the method with a null seriesContainer, it gets sliced once again, but this time it contains the data added by the previous bed. Since I am utilizing slice(), I expected to just obtain the value of LINECHART2_DATA, not the reference. What could be causing this issue?

Answer №1

According to the explanation on the Array.slice documentation:

The slice function does not modify the original array. Instead, it creates a shallow copy of the elements from the original array. The copied elements are handled differently based on their type:

When dealing with object references (and not the actual objects themselves), slice copies the references into the new array. This means that both the original and new arrays point to the same object. Any modifications made to the referenced object will be reflected in both arrays.

For strings, numbers, and booleans (excluding String, Number, and Boolean objects), slice directly copies the values into the new array. Changes made to these data types in one array do not impact the other array. Additionally, adding a new element to one array does not affect the other.

The observed behavior is a result of slice's shallow copy approach. If you require a deep copy for independent object mutation, manual cloning is necessary. Various methods for achieving this can be found in responses to this question.

Answer №2

In order to avoid changing the elements of a duplicated array, it is important to also clone the items within it:

 bed.seriesContainer = LINECHART2_DATA.series.map((item=>Object.assign({}, item, {data: item.data.slice()}))

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

Displaying Data in Table Using Ajax Request

I'm working on a project that involves creating an HTML table from an ajax request pulling SharePoint list items. The screenshot provided demonstrates how it functions and what it displays after the button is clicked. However, I am looking for a way t ...

An error occurred due to a state update being attempted on an unmounted component. The solution is to properly cancel all subscriptions and asynchronous tasks in a

Currently, I am attempting to utilize ListEmptyComponent within a FlatList. If there is no data present, I intend to display ListEmptyComponent={} However, in the Loadingsecond component, I am using useEffect to render when loading is true; if there is s ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

SCORM-compliant Angular web application bundle

As I work on my angular web project, I am looking to create a SCORM package in order to easily integrate it into any LMS system. I have a few questions regarding the packaging process and compatibility: What is the best way to package my project for SCORM ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

Angular: Showing the Gap between Basic Elements within an Array in the Template

I've been working on displaying a nested JSON object in a table, where there is an array of strings like obj.someKey = ['a','b','c']. Currently, I am directly showing the array content in the td tag of the table. <td ...

express has a req.body that is devoid of any content

When making a request to my local server in my React app, the code looks like this: fetch("http://localhost:4000/signup", { method: "POST", mode: "no-cors", body: JSON.stringify({ name: "Joe", lname: "Doe& ...

Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process. According to the Webpack .md file: exclude Type: String|RegExp|Array Default: undefined This setting is used to spe ...

Getting information from a JSON file with several variables: A guide for using node.js, express, and jQuery

In order to minimize the number of Ajax calls, I am attempting to send three variables in a single Ajax response. However, I am facing difficulties when trying to process the data on the client side. Let me elaborate on my issue and if sending multiple var ...

replace the standard arrow key scrolling with a new custom event

Currently, I am in the process of creating a unique scroll box to address my specific needs. The standard html <select> box is not cutting it for me as I require two columns displayed, which I couldn't achieve with a regular <select>. Howe ...

Troubleshooting an Issue with Image Loading in Angular's UI-Bootstrap Carousel

var app = angular.module('app',['ui.bootstrap']) app.controller('getResources',['$scope',function($scope){ $scope.myInterval = 5000; $scope.noWrapSlides = false; $scope.active = 0; var slides = $scope ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Searching for a value within an array of objects using JavaScript: The ultimate guide

Similar Question: Locate specific object by id within a JavaScript objects array What is the best way to determine if a value exists in a given JavaScript array? For instance: var arr = [ {id: 1, color: 'blue'}, {id: 2, colo ...

Can you explain the term 'outer' in the context of this prosemirror code?

Take a look at this line of code from prosemirror js: https://github.com/ProseMirror/prosemirror-state/blob/master/src/state.js#L122 applyTransaction(rootTr) { //... outer: for (;;) { What does the 'outer' label before the infinite loop ...

A versatile generic type infused with dynamic typing and optional parameter flexibility

Looking to develop a function that can accept an optional errorCallback parameter. In cases where the consumer of this function does not provide a callback, I aim to default to a preset handler. The key criteria here are strong typing and utilizing the ret ...

Please ensure that all fields in the form are filled out before clicking the enable button

Is it possible to enable the button only when all fields are filled out in a form? It's easy if there's just one field, but I have multiple fields with a select field as well. I'm not sure how to do this. Here's the form I've creat ...

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

Two unnamed objects cannot be combined using the AsyncPipe

Currently, I am looking to implement an autocomplete feature using Angular Material in Angular 8. Below is a snippet of the code used in the TypeScript file: @Input() admins: User[]; userGroupOptions: Observable<User[]>; filterFormFG: FormGrou ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...