The array's value was altered without any direct modification

In an attempt to prepend an element to a new array and return the modified array, I wrote the following code. Although it works, returning the original 'arr' instead of the modified 'newArr' results in changes to the 'arr'.

function addToFrontOfNew(arr, element) {
  newArr = arr;
  newArr.unshift(element);
  return newArr;
}

If I were to modify the code as shown below:

 function addToFrontOfNew(arr, element) {
  newArr = arr;
  newArr.unshift(element);
  return arr;
}

And then test the function with addToFrontOfNew([1,2], 3), the output would be [3, 1, 2].

I'm seeking guidance on how to restructure the function so that only the 'newArr' is modified without affecting the original 'arr'.

Answer №1

It's important to clone the original array instead of referencing it directly. One approach is:

function addElementToFront(arr, item) {
  let newArray = arr.slice();
  newArray.unshift(item);
  return newArray;
}

The slice() method creates a shallow copy... For more information, check out this link.

Answer №2

function addElementToStart(arr, item, rvOption)
{
    var length = arr.length;
    var newA = [];

    for(let j=0; j<length; j++)
    {
        if (j===0) {
            newA = [item, arr[0]];
        } else {
            newA.push(arr[j]);
        }
    }

    switch(rvOption)
    {
        case 'original':
            return arr;
        break;

        case 'new':
            return newA;
        break;
    }

}
var fruits = ['oranges','grapes','kiwis'];
var newItem = 'peaches';

console.log(addElementToStart(fruits,newItem,'original'));
console.log(addElementToStart(fruits,newItem,'new'));

** MODIFIED THE FUNCTION TO ADDRESS USER FEEDBACK **

This revised code now features a switch statement to allow users to choose whether they want the original array or the newly added element at the beginning of the array. It loops through the initial array, and inserts the new item at the start when the index is 0, while pushing all subsequent elements onto the new array in sequence. The switch statement facilitates customized output based on user preference. For implementation in HTML tags using jQuery, simply use .toString() along with the function.

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

Utilize jQuery to interact with a Web API web service

Okay, so go ahead and roast me in 27 different languages if you want, but here's my dilemma: I've delved into creating a web service using the .NET 4 Web API. I've coded a method named GetTransaction that simply returns a string. It's ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

Navigation menu automatically scrolls to the top instantaneously

Update: Apologies for the previous issues encountered with offline hosting. Upon transferring everything to the domain, the problem has been resolved. However, a lingering question remains about why the website loaded incorrectly when all files were kept i ...

FullPage.js combines traditional scrolling with a unique horizontal slider feature

Visit this link for the example. Hello, I have a question regarding this example: Is there a way to disable the automatic scrolling that occurs when reaching the middle of a page? Also, I am having trouble with the horizontal slider not responding to ...

Use Jquery to apply quotation marks within a blockquote

Here is the code I am working with: $("input[id="+id.slice(0,-1)+"-br-"+brand+"].qnt_to_cart").show(); This code generates: input[id=02620-br-FEBI BILSTEIN].qnt_to_cart However, I need it to look like this instead: input[id="02620-br-FEBI BILSTEIN"].q ...

Using Ajax for updating table content on a JSP webpage section

I am working on implementing Ajax functionality for a table to enable partial updates every hour. Below is a snippet of my JSP code: < head > < meta http - equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < titl ...

AngularJS Setting Default Values in HTML Pages

My goal is to set the default value for a dropdown in an Angular HTML Page. The page uses tabs, and I want the default value to load when a specific tab is clicked. <div class="col-md-9" ng-cloak ng-controller="ServiceTypeController"> <md-conten ...

Fade in background color with jquery when scrolling

Is there a way to make the header background fade in after scrolling a certain number of pixels? The code I have sort of works, but not quite right. Any suggestions? Thank you! $(function () { $(window).scroll(function () { $(document).scrol ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

Updating Material in Three.js during Execution

I've got some .js files that were exported from Blender, and I'm loading them using THREE.JSONLoader(); In my callback function: var callback = function( geometry ) { createMesh(geometry); For loading the file: loader.load( "Models/sculp.js ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Encountering an error when using Angular Material virtual scroll in conjunction with Angular-UI

Trying to incorporate Angular material's virtual scroll feature on angular-ui-tree is proving to be a bit challenging. The error message that keeps popping up is: Controller 'uiTree', which is required by directive 'uiTreeNode', ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

Managing an iframes website using buttons and links: Tips and tricks

I am trying to create a website that includes an iframe for navigating through external websites using previous and next buttons. I also want to display the links on a sidebar so that users can click on them to automatically load the site in the iframe. I ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

Utilizing AngularJS to upload numerous independent attachments to CouchDB

My goal is to upload multiple files to a couchdb document using angularjs. Despite my efforts with an angular.forEach loop, I am facing issues as the asynchronous $http calls do not wait for the previous loop to finish before moving on to the next one. Her ...

How can you use JavaScript to identify resize or zoom changes across all ancestor DOM elements?

I have a DOM element that consists of a chart. <div id="plot1" class='plot-chart'></div> This specific DIV can be nested within various other DIVs. <div id="one" style="width:100%;height:100%;zoom:0.9;"> <div id="two"& ...