Introducing a fresh addition to the array

I am looking for a way to create a new array without modifying the original one. Currently, there is a function that adds a new object to an existing array, but I need a different method to achieve this. Can someone suggest a solution?

const arr = [
   {  
     "name":"BMW",
     "price":"55 000",
     "country":"Germany",
     "certificate":"yes"
  },
  {  
    "name":"Mitsubishi",
    "price":"93 000", 
    "constructor":"Bar John",
    "door":"3",
    "country":"Japan",
  },
  {  
    "name":"TOYOTA", 
    "price":"48 000", 
    "max_people":"7",
    "country":"Japan",
    "certificate":"yes"
  },
  {  
    "name":"Volkswagen",
    "price":"36 000", 
    "constructor":"Pier Sun",
    "country":"Germany",
    "certificate":"no"
  },
 ];
function pushArr (arr, item){
    arr.push(item); 
}

let Cars = pushArr(arr,{  
  "name":"Audi",
  "price":"89 000", 
  "constructor":"Hubert Trumpius",
  "country":"Germany",
  "certificate":"yes"
});

console.log(arr);

Answer â„–1

If you're looking to combine arrays in JavaScript, you have a couple of options - you can either use Array.concat() or employ the spread syntax:

function mergeArrays(firstArray, secondArray) {
  return firstArray.concat(secondArray); // or simply: [...firstArray, ...secondArray]
}

const firstArray = [{"name":"BMW","price":"55 000","country":"Germany","certificate":"yes"},{"name":"Mitsubishi","price":"93 000","constructor":"Bar John","door":"3","country":"Japan"},{"name":"TOYOTA","price":"48 000","max_people":"7","country":"Japan","certificate":"yes"},{"name":"Volkswagen","price":"36 000","constructor":"Pier Sun","country":"Germany","certificate":"no"}];

let combinedArray = mergeArrays(firstArray, {
  "name": "Audi",
  "price": "89 000",
  "constructor": "Adolf Trump",
  "country": "Germany",
  "certificate": "yes"
});

console.log(firstArray === combinedArray);
console.log(combinedArray);

Answer â„–2

The reason behind this behavior is that JavaScript objects, which also include arrays, are passed by reference, while scalar values are passed by value.

When you pass objects to functions and directly modify them, you are essentially working with the same object in memory.

To prevent unintentional mutations of your object, it's important to create a new instance of the object before making any changes. There are several methods to achieve this:

const arr = [{
    "name": "BMW",
    "price": "55 000",
    "country": "Germany",
    "certificate": "yes"
  },
  {
    "name": "Mitsubishi",
    "price": "93 000",
    "constructor": "Bar John",
    "door": "3",
    "country": "Japan",
  },
  {
    "name": "TOYOTA",
    "price": "48 000",
    "max_people": "7",
    "country": "Japan",
    "certificate": "yes"
  },
  {
    "name": "Volkswagen",
    "price": "36 000",
    "constructor": "Pier Sun",
    "country": "Germany",
    "certificate": "no"
  },
];

//destructure your argument here 
function pushArr([...arr], item) {
  return [arr, item];
}

let Cars = pushArr(arr, {
  "name": "Audi",
  "price": "89 000",
  "constructor": "Adolf Trump",
  "country": "Germany",
  "certificate": "yes"
});

console.log(arr);
console.log(Cars);

It's crucial to remember that re-assigning your object will not update its value. For more details on this concept, refer to Call by sharing.

Answer â„–3

If you want to duplicate an array, try using the slice function.

function addToArray(arr, item) {
    let clone = arr.slice();
    clone.push(item);
    return clone;
}

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

Exploring the world of Django and JSON POSTs in the realm of Google API mania

Project Overview I am currently developing an application aimed at assisting users in finding rides. My tech stack includes Django, Python 2.7, and integration with Google Maps and Directions APIs. Within a specific view, I present a map where users can ...

How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to ...

Is there a way to dynamically inject a stylesheet in NextJS?

I'm facing a challenge in my nextJS application where I need to dynamically load a stylesheet based on the user preference fetched from the database. To achieve this, I have added the stylesheet link in the Head component (next/head) like so: <Hea ...

Using ReactJS and Ruby on Rails to implement an AJAX delete request

There is a component named Items residing inside a parent component called ItemsContainer. A click on a button within the Items component triggers an Ajax function to delete that specific Item. However, I am encountering a 500 error message at the moment ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Tracking the number of div elements using the variable i

In my coding project, I have implemented a functionality where each time I create a new div element, the variable 'i' representing the number of divs increases. However, I also need it to decrease dynamically when I delete a div without needing t ...

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Spring MVC applications might experience slow loading times when loading RequireJS libraries

Recently, I integrated RequireJS into my Spring MVC application to manage dependencies for various libraries, including jQuery and jQuery UI. Although I have successfully implemented it, I am facing an issue whenever the page is loaded or refreshed. Initia ...

Having trouble displaying dynamically added images in my jsx-react component. The images are not showing up as expected

import React from "react"; import ReactDOM from "react-dom"; var bImg = prompt("Enter the URL of the image you want to set as the background:"); const bStyle = { backgroundImage: "url(bImg)"; // The link is stored ...

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

Performing CRUD operations on arrays within arrays in MongoDB includes inserting, updating, and deleting elements within a complex nested structure

Take a look at this particular document: { "entity_id" : 10, "features" : [ { "10" : "Test System 2" }, { "20" : "System 2 Description" }, { "30" : ["Free", "Monthly", "Quaterly"] }, { ...

Is it possible to utilize Babel for transpiling, importing, and exporting in the client, all without relying on Web

Is it possible to compile JSX and export variables through the global namespace using Babel? I'm not interested in setting up a Webpack server. I'm currently familiarizing myself with ES6, JSX, Babel, and React, and I find adding another librar ...

"Is there a way to retrieve the file size from a source on a different site

Hey everyone, I'm pulling src's from another website and have them in an array like ["www.another.com/pic1.png", "www.another2.com/pic2.jpg"]. I tried using XMLHttpRequest and checking the file.size, but CORS restrictions are preventing me from ...

The useEffect hook in React initially returns an empty array

Retrieving data from my database involves the following steps: const clicked = props.clicked; const [allEmployees, setAllEmployees] = useState([]); const [list, setList] = useState([]); useEffect(()=>{ //fetching employees Axios.get( ...

Personalize the appearance of your stackLabels in Highcharts with dynamic customization options

I recently created a bar graph using Highcharts. You can check it out here: http://jsfiddle.net/v1rbz41q/3/ Here's the code snippet I used: chartw.yAxis [0] .options.stackLabels.formatter = function () {              return "werfdc";   ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Unforeseen alteration of initial element's value in a 2D string array following the process of forking

I have developed a shell program that can handle piping of user input. The program is designed to split the input into segments based on the presence of pipes, store them in an array, and then fork the parent and child processes. However, I have encountere ...

Always Seek Permission for Geolocation in Cordova

Is there a way in PhoneGap to update the Geolocation plugin's permissions from "while in use" to "always" without manually editing the .plist file? I noticed that changing the NSLocationAlwaysUsageDescription key in the project's config.xml sets ...