How does the rest operator in Javascript work when dealing with a different array input?

The following code snippet shows a function that uses Insertion Sort to sort an array of heights. The values being passed in are 4, 1, 9, 14, 6, and 8, and the sorted order should be 1, 4, 6, 8, 9, 14.

var heightChecker = function(heights) {

    var sorted = [...heights];
    var newHeight = insertionSort(heights);
    var count = 0;
    
    for(var i = 0; i < newHeight.length; i++) {
        if(newHeight[i] !== sorted[i]) {
            count++;
        }
    }

    return count;
}

When using the line var sorted = [...height];, the expected answer is 3. However, changing the code to:

var heightChecker = function(heights) {

      var newHeight = insertionSort(heights);
      var count = 0;
      
      for(var i = 0; i < heights.length; i++) {
          if(newHeight[i] !== heights[i]) {
              count++;
          }
      }
  
      return count;
  }

Returns an answer of 0 instead. It's puzzling why the two implementations yield different results despite appearing similar.

Below is the Insertion Sort algorithm used in the code:

function insertionSort(inputArr) {
    let n = inputArr.length;
    for (let i = 1; i < n; i++) {
        let current = inputArr[i];
        let j = i - 1;
        while ((j > -1) && (current < inputArr[j])) {
            inputArr[j + 1] = inputArr[j];
            j--;
        }
        inputArr[j + 1] = current;
    }
    return inputArr;
}

Answer №1

Using a spread operator like this: <code>a = [...b]
, allows you to create a copy of array b. On the other hand, simply doing a = b will result in 'a' being just another reference pointing to the same array.

let a = [1,2,3];
b = a;
c = [...a];
a[1] = 41; // changes values of both a and b
b[1] = 42; // also changes values of both a and b
c[1] = 43; // only alters value of c
console.log(a); // prints 1, 42, 3
console.log(b); // displays 1, 42, 3
console.log(c); // outputs 1, 43, 3

Alternatively, here's how it looks with a function call:

function addNumber(array, number) {
  array.push(number);
}
let a = [1,2,3];
b = a;
c = [...a];
addNumber(b, 4); // now a contains [1,2,3,4]; and b refers to [1,2,3,4] (same as a); while c holds [1,2,3]
addNumber(c, 5); // even though a still is [1,2,3,4]; c has changed to [1,2,3,5]

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

Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

Load Bootstrap CSS file externally on a website dynamically

Although my knowledge of JavaScript is limited, I am the recipient of a small web application from a friend that is being utilized by multiple companies. As each company requires specific modifications in the appearance and CSS of certain webpages, it can ...

Learn how to retrieve the HTTP headers of a request using AngularJS

When working with AngularJS, I know that accessing an HTTP request's GET parameters is easy using: $location.search().parameterOfInterest But how can I access the HTTP headers of the request? It's worth noting that I'm not utilizing $http ...

Design a function that accepts a string parameter and outputs an encoded (h4ck3r 5p34k) rendition of the input string

function convertToHacker(str){ for (var i=0; i <str.length;i++) { if (str[i]==="a") {str=str.replace("a","4")} else if (str[i]==="e") {str=str.replace("e","3")} else if (str[i]==="i") {str=str.replace("i","1") ...

Having a hard time finding the perfect styling solution for Material UI

Is there a way for me to customize the styling of Material UI's components in addition to their default rules by injecting my own CSS? I'm unsure how I would go about setting these parameters using the styled-components API. Is this even doable? ...

Ways to insert a hyperlink within a div element

Consider the following HTML structure: <article id="1919"> <div class="entry-content clearfix"> <div></div> <div></div> </div> </article> &l ...

Troubleshooting type casting issue in Typescript when working with objects containing getters and setters

I'm facing an issue with the code snippet provided. I suspect it might be related to casting, but I'm unable to pinpoint the exact solution. interface Code { code: string; expiration: number; } interface IActivationCode { [userId: string] ...

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

Can Angular-Material help create a sidenav that toggles on and off?

I am struggling to create a side menu that remains closed by default on all screen sizes and always opens on top of other content. Despite my efforts, it keeps switching at widths over 960px. This is the current code for my menu: <md-sidenav is-locked ...

Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out ho ...

Display a component just once in React or React Native by utilizing local storage

I am struggling with a situation where I need to display a screen component only once using local storage. It's really frustrating. App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } component ...

Retrieve a directory listing from user input

I have a file input field that allows the user to select multiple images using this code: <input type="file" id="file" name="file" accept="image/*" multiple>. I am trying to pass all selected images to my FormData object as shown below: var formdata ...

Show the button only when the text is updated

Is there a way to display a button only when the quantity of items in the cart changes, similar to the eBay shopping cart feature? I was able to implement it but it's not functioning as expected. Here is the link to what I have so far. Does anyone kno ...

Using Vue.js to update content in input files

I have a Vue.js template file that includes data containing various documents. Within the page, there is a table with rows that feature upload file input buttons, structured like this: <tr v-for="(doc, index) in documents"> <td :id="'doc-& ...

The onProgress event of the XMLHttpRequest is triggered exclusively upon completion of the file upload

I have a situation with my AJAX code where the file upload progress is not being accurately tracked. The file uploads correctly to the server (node express), but the onProgress event is only triggered at the end of the upload when all bytes are downloaded, ...

Page for users to login using React

Struggling to create a login page in React due to the asynchronous nature of setState. Upon submission, the state is not updating with form values, only displaying old initial values. How can I ensure that the submit function receives the new values? Is ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Is Json Patch in contradiction with the principles of REST?

Is it against REST principles to use Json Patch? Will my API still be considered RESTful if I implement it? { "op": "replace", "path": "/biscuits/0/name", "value": "Chocolate Digestive" } ...

The correct terminology for divs, spans, paragraphs, images, anchor tags, table rows, table data, unordered lists, list

Just wondering, I've noticed that every time I come across a page element '<###>[content]<###>' and want to learn how to manipulate it, I usually search for something like "how to do x with div" or "how to get y from div". I know ...