Transferring elements from one array to multiple arrays

I have been working with the basics of JavaScript arrays and here is my code snippet:

let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let new_arr = [];

new_arr = new_arr.concat(arr);
console.log(new_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

new_arr[2].pop();
let sub_arr = [];
sub_arr = sub_arr.concat(arr);

console.log(sub_arr); //output: ['students', 'exams',[{'sub1':80, 'sub2':60}]]

The expected output for sub_arr is

['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]] 

I attempted to use slice() but it did not yield the desired results. Please assist me with this issue.

Answer №1

To achieve what you need, you can perform a deep clone using JSON.parse and then JSON.stringify.

let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let new_arr = [];

new_arr = JSON.parse(JSON.stringify(arr));
console.log(new_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

new_arr[2].pop();
let sub_arr = [];
sub_arr = sub_arr.concat(arr);

console.log(sub_arr); //output: ['students', 'exams',[{'sub1':80, 'sub2':60}]]

Answer №2

If you want to create a deep copy of your array, here's how you can do it:

const makeDeepCopy = (obj) => JSON.parse(JSON.stringify(obj));


let originalArray = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let copiedArray = [];

copiedArray = copiedArray.concat(makeDeepCopy(originalArray));
console.log(copiedArray); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

copiedArray[2].pop();
let subArray = [];
subArray = subArray.concat(makeDeepCopy(originalArray));

console.log(subArray); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

Answer №3

If you want to create a deep copy of an object, you can achieve this using a recursive function like the one demonstrated below:

const originalObj = [ 'books', 'pens', [
  { 'type1': 'gel', 'type2': 'ballpoint' },
  { 'brand_type1': 'Pilot', 'brand_type2': 'Bic' }
]];

const createCopy = (input) => {
  if (input == null) {
    return null;
  } else if (typeof input === 'string') {
    return input;
  } else if (Array.isArray(input)) {
    return input.map(item => createCopy(item));
  } else if (typeof input === 'object') {
    return Object.fromEntries(Object.entries(input)
      .map(([key, value]) => [key, createCopy(value)]));
  } else {
    return input;
  }
};

const copiedObject = createCopy(originalObj);

console.log(copiedObject);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Sending an array and an object simultaneously through a single ajax request

I previously inquired about passing an object to an ajax request for my rest service. Now I am wondering if it's possible to pass both an array and an object within a single ajax request. Any insights on this matter would be greatly valued. ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Tips for populating a dictionary with a large datalist of around 2000 items

Currently, I'm facing an issue where the code I'm using takes about 10 seconds to run on Chrome and around 2 minutes on IE11, which is the primary browser it will be used with. for (var key in dict) { if (dict.hasOwnProperty(key)) { ...

Calculate the total of items in an array based on a different regular item in the same row using PHP

Here is a basic example of an array used in my PHP code. The original array is populated automatically by queries. I am trying to find a simple way to calculate the total of all "number" indexes in different rows with the same "fruit" index. For instance, ...

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

What is the best way to customize the appearance of chosen selections in the MUI Autocomplete component?

I'm currently facing an issue with changing the style of selected options in MUI when the multi option is enabled. My goal is to alter the appearance of all highlighted options. Any assistance on this matter would be greatly appreciated, thank you! ...

Is it possible to set a value for a jQuery function after the function has

I am a beginner when it comes to javascript & jQuery. I am currently working on a feature for my website where users can display badges they have earned on their own site by simply copying and pasting a bit of code that I provide. Although the javascript p ...

Retrieving data arrays from response.json

I've been on a wild goose chase trying to solve this puzzling issue. RAWG has transitioned to using their own API instead of Rapid API for game reviews, and I'm in need of data for "Tom Clancy Rainbow Six Siege". Despite my efforts to convert t ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

Experiencing difficulties when establishing a connection between MongoDB and Node.js

I'm encountering an issue when attempting to connect MongoDB and Node.js on my local server. Can anyone assist me with solving this problem? Below is my JavaScript code: const mongodb = require("mongodb"); // Provide the function to connect to the d ...

Annoying scrolling issue arising from using jQuery Buttonset

Dealing with jQuery UI buttons and buttonsets has been quite a challenge for me. Despite searching extensively on this site, I have yet to find a satisfactory solution that works smoothly. My setup includes jQuery rev 1.11.1 and jQuery UI rev 1.9.2. The i ...

Hide an Angular button when a page is loaded, depending on the information found in a table

How can I hide the Submit button in a table row if a certain condition is met based on information from the database? I attempted to create a function that returns true or false, but it ends up crashing my program because it runs continuously. I also trie ...

Challenges arise when using Bootstrap 4 for country selection

There have been reports that bootstrap 4 country select is not functioning properly. In an effort to troubleshoot, I delved into the documentation to find a solution. To make bootstrap-select compatible with bootstrap 4, refer to: Bootstrap 4 beta-2 ...

Triggering a button click to upload a file from within a grid view

I'm having trouble uploading a file when the "Fileupload" control inside gridview changes. I want to save the file content in DB as soon as it is uploaded by the user. I tried manually triggering the click event of the button control on the change of ...

Visual Studio encountered a termination error with the preLaunchTask 'build', resulting in exit code 129

After setting up Visual Studio on my Linux Mint device, I encountered an issue when trying to execute a C# program. The error message displayed was: The preLaunchTask 'build' terminated with exit code 129. Although it gives me the option to Deb ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

Using jQuery to initialize a slider with data obtained from a JSON request, which is retrieved from a PHP script

Currently, I am facing a challenge where I need to set up a jQuery Slider using data obtained from a PHP-SQL query that has been encoded into JSON format. The PHP side is functioning properly, but I am encountering difficulties in parsing the value (as th ...

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...