The outcome from employing array.splice was totally unforeseen

I devised a JavaScript method to select items from an array and display the final item. However, I noticed that this process was inadvertently removing items from the original array.

Here is the function:

function oneRemaining(arr) {
    tmp = arr;
    while (tmp.length > 1) {
        tmp.splice(~~(Math.random() * tmp.length), 1);
    }
    return tmp[0];
}

After executing this function, the initial array should remain unchanged because it was not supposed to be modified. Unfortunately, when I tested it in the console, only one item was left in the array.

What could be causing the input array to be altered?

Answer №1

The reason your array is changing is because of the following factors:

  1. Instead of creating a copy or clone, you created a reference which means you are manipulating the original array.
  2. Splice directly modifies the underlying array, making it one of the few methods that do so (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)

To prevent this issue, consider replacing your second line with:

tmp = arr.concat([])

I hope this information proves to be useful for you.

Answer №2

The transformation is occurring due to the fact that tmp points to arr rather than being a duplicate of it. Any modifications made to a referenced object will also affect the original.

Answer №3

Arrays in JavaScript are considered reference types, meaning that when you assign a variable to an array, you are actually assigning a reference to that array rather than making a copy of it. This means that any changes made to the variable will affect the original array in memory.

tmp = arr;

If you want to create a true copy of your input array, you can use the .slice(0) method on the array.

(Also, don't forget to include the var keyword before declaring the tmp variable, unless you intend for it to be global.)

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

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

Leetcode problem 833 deals with replacing strings based on their index positions

Accessing Values by String IndexThis specific query is linked to a prior inquiry. Example 1: Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] Output: eeebffff Explanation: a is found at index 0 in S and is replaced by eee ...

What is the best way to send a variable to inline javascript via the EJS templating engine?

I have a list of buttons and text in HTML generated from an array named items within an .EJS template. How can I pass the specific item's id (item.id) to the button's function so that I can correctly send the data to my API? Thank you. <!DOCT ...

Modify the javascript addEventListener to use 'scroll' instead of 'wheel'

I am currently attempting to modify this javascript event to trigger on scroll instead of the mouse wheel. I have attempted to make the following changes: window.addEventListener('wheel',function (e) changed to window.addEventListener('sc ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

Implementing complex routing with Express.js on top of Node.js

Recently delving into the world of javascript, I have embarked on creating a RESTful API using Node.js and Express.js Here is the breakdown of my directory structure: /server.js /api/api.js /api/location/location.js My goal is to make the API modular, ...

Looking to display outcomes on a separate line every time you click? Currently developing a project involving Rock, Paper, Scissors

I have been tackling the Rock Paper Scissors project from The Odin Project. Take a look at the interface I have developed so far: My goal is to display the results on new lines every time a button is clicked. Instead, they are appearing next to each oth ...

Error: cannot assign 'int*' to 'int [0]', the types are incompatible and will not compile

Here's the code I'm working with: #include "../include/Enemy.h" Enemy::Enemy(int X[], int Y[], int Type ) { x=X; y=Y; type=Type; } Enemy::~Enemy() { //dtor } Header File: #ifndef ENEMY_H #define ENEMY_H class Enemy { p ...

I just can't seem to grasp pointers in C no matter how hard I try

Currently, I am studying the concept of C pointers using this PDF. The code snippet provided below was intended as an example, but it caused confusion for me. Initially, my understanding was that pointers to arrays point to the memory address of the first ...

Is it possible to attach React Components to Elements without using JSX?

In my React Component, I have the following code: import React, { useEffect } from 'react' import styles from './_PhotoCollage.module.scss' import PhotoCard from '../PhotoCard' const PhotoCollage = ({ author }) => { let ...

How come WhatsApp is not recognizing my og:tags correctly?

I'm having an issue with my webpage where the og:tags generated for link previews on Facebook work fine, but they can't seem to be scraped by WhatsApp. Even though the tags are correct in the source code of the site, WhatsApp shows an error messa ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Tracking changes in an email input using Angular's $watch functionality

I am currently working on creating a custom directive to manage form input errors. Here is what I have so far: directive('input', function() { return { restrict: 'E', scope: true, link: function (scope, elem ...

Troubleshooting RangeError in AngularJS $routeParams: Exceeding maximum call stack size

While using AngularJS v1.5.9 and $routeParams, I am encountering repetitive errors in the console of my Chrome browser. RangeError: Maximum call stack size exceeded at la (angular.js:10097) at p (angular.js:9492) at g (angular.js:8757) at ...

Why doesn't Bootstrap have access to the tab view obtained on _Layout.cshtml when it is clicked?

Currently, I am working on an MVC-5 project using Bootstrap and have all my links in _Layout.cshtml. I have a drop-down tabs feature like this: http://prntscr.com/76jfba (implemented using Bootstrap, visible on Visual Studio project launch). In my _Layout. ...

display the returned value in the database function before rendering response

I am trying to create a helper function that will be used in my Pug view. I send a function as data to the view file, but I am facing an issue where my helper function does not return a value or returns undefined in my Pug view. Can someone help me with th ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

Thumbnail Carousel Caption in Bootstrap 3

Is it possible to create a Bootstrap 3 carousel where the image changes when the mouse cursor hovers over the thumbnail under the carousel? Currently, I have a setup with the carousel and thumbnails below it. Typically in Bootstrap, the image changes autom ...