Randomly reorganize elements in a JavaScript array

I am facing an unusual issue while shuffling an array in JavaScript and I am unable to identify the root cause. Can someone provide assistance?

When attempting to shuffle an array, the output I receive is unexpected:

[1,2,3,4,5,6,7,8,9,10]

Instead of the desired result, I encounter null values as shown below:

[null,10,1,8,9,3,2,7,6,4]

Below is the code snippet (http://jsfiddle.net/2m5q3d2j/):

Array.prototype.suffle = function () {
    for (var i in this) {
        var j = Math.floor(Math.random() * this.length);
        this[i] = this[j] + (this[j] = this[i], 0);
    }

    return this;
};

Answer №1

In order to add the enumerable property shuffle to Array.prototype, a hasOwnProperty test is necessary if you choose to iterate using for-in:

Array.prototype.shuffle = function () {
    for (var i in this) {
        if ( this.hasOwnProperty(i) ) {
           var j = Math.floor(Math.random() * this.length);
           this[i] = this[j] + (this[j] = this[i], 0);
        }
    }

    return this;
};

Alternatively, it is recommended to use the following approach:

Array.prototype.shuffle = function () {
    for (var i=0; i < this.length; i++) {
        var j = Math.floor(Math.random() * this.length);
        this[i] = this[j] + (this[j] = this[i], 0);
    }

    return this;
}

http://jsfiddle.net/2m5q3d2j/5/

For ES5+ engines, it is possible to use Object.defineProperty to create the property without making it enumerable.

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 the power of JavaScript or Lodash to substitute a string

Dealing with a scenario where a string contains multiple links that need to be replaced with actual HTML links, for example: <a href=”http://www.testing.com” target=_blank>http://www.asdfasd.com</a> Sample text: http://www.testing.com Sim ...

I am looking to identify when the focus event occurs on all HTML input elements on a page without using addEventListener or any HTML attributes

Does anyone know a way to detect the focus event on all HTML input elements on a page without using the addEventListener function or HTML attributes? I was successful in detecting click events with the following code: onclick = () => { // do somethi ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...

Locate the position of the cursor within a rectangular shape

I'm struggling to determine the location of a cursor within a rectangle, specifically which part (one of 4 triangles) it is in. This visual representation helps me grasp it better than any explanation I can come up with :s Working in javascript (whe ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

When using the executeScript() method, it unexpectedly gives a null result instead of allowing me to scroll

The following code snippet is used to scroll horizontally within a web page: WebElement element=driver.findElement(By.xpath("//div[@class='table-wrapper']")); JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("arguments[0].scroll ...

When performing an Angular HTTP post, additional parameters are automatically included in the request

Within a directive, I have the following code block: scope.progressCourse = -> req_data = course_id: scope.course.id success: true $http.post( "<%= Rails.application.routes.url_helpers.progress_course_path %>", req_data ).t ...

To retrieve the first td element by clicking a button within the corresponding row using JQuery

This may seem like a straightforward inquiry, but despite my best efforts, I have been unable to find a solution. I am looking to create a function that will allow me to click a button located in the 3rd td element and display the text from the first td e ...

creation of objects using constructors in Node.js

As I delve into the world of Node.js, a burning question has arisen - how can I make a function accept multiple strings in the form of an array? Picture this scenario: export default (config: Config) => { return { target: 'https://google.com ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Utilizing Command Line Arguments in C Programming

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int args, char *argv[]) { int i = 0; for (i = 0; i < args; i++) printf("\n%s", argv[i]); return 0; } If I input "dog" into the program right ...

Is it possible to pass variables into a factory function?

I have a factory that is a wrapped $resource object and I am trying to include a custom header for http authentication. However, I am struggling to figure out how to pass data into the header. app.factory('SomeFactory',['$resource', fu ...

transfer data between JavaScript and PHP

I have set up a dynamic table structure in my project: <form method="POST" action="recieve.php"> <table> <thead> <th>Value</th> <th>Action</th> </thead> <tbody> <tr> ...

Showing information in a tree structure using HTML, CSS, and JQuery

Trying to figure out how to present a large amount of data in a tree structure. Each node could have multiple children and parents, requiring a dynamic representation. I've explored various JavaScript libraries like D3 and Raphael, but unfortunately, ...

Is it possible to retrieve a physical address using PHP or Javascript?

Is it possible to retrieve the physical address (Mac Address) using php or javascript? I need to be able to distinguish each system on my website as either being on the same network or different. Thank you ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

How can I modify a PHP file to be compatible with Ajax functionality?

I'm currently exploring the world of CodeIgniter and facing some challenges with AJAX. This is my first time working with it, so I have quite a few questions popping up. What I'm looking for: I want to be able to post data using AJAX and retrie ...

What could be causing these errors to occur when I use the fetch API?

Having trouble fetching the news API and getting this error message: TypeError: Cannot read properties of undefined (reading 'map'). Any suggestions on fixing this issue? Your help is much appreciated. import React, { Component } from 're ...

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...

What's the best way to align several buttons in the center of the screen horizontally?

I'm struggling to properly align divs with images inside another div. My goal is to insert buttons into my HTML and use jQuery to center them automatically, but I can't seem to get it right. You can view the fiddle I've created here: http:/ ...