Unexpected Results when Sorting Objects by Value

When attempting to organize 2 objects based on the value of first_name, one in ascending alphabetical order and the other in descending order, both end up being sorted in descending order. What could be the mistake in this code? The objective is to rearrange the objects in the array according to the first_name value.

var participants = [
  {
    id: "992543",
    first_name: "",
    last_name: "",
    company: null,
    notes: "",
    registrationType: "",
    alerts: [ ],
    reg_scan: null
  },
  {
    id: "999070",
    first_name: "Tori",
    last_name: "Fullard",
    company: null,
    notes: "",
    registrationType: "Staff",
    alerts: [ ],
    reg_scan: null
  },
  {
    id: "99265",
    first_name: "Ronald",
    last_name: "Brown",
    company: null,
    notes: "",
    registrationType: "Dean's Guest",
    alerts: [ ],
    reg_scan: null
  },
  {
    id: "992279",
    first_name: "Laila",
    last_name: "Shetty",
    company: null,
    notes: "",
    registrationType: "Table Guest",
    alerts: [
      {
        alert_id: "1",
        dismissed: "0"
      }
    ],
    reg_scan: null
  },
  {
    id: "992248",
    first_name: "Paul",
    last_name: "Keenan",
    company: null,
    notes: "",
    registrationType: "Table Guest",
    alerts: [ ],
    reg_scan: null
  }
];

var az_part = participants;
var za_part = participants;
az_part.sort(function(a, b) {
    var nameA = a.first_name.toLowerCase();
    var nameB = b.first_name.toLowerCase();
    if (nameA > nameB) return 1;
    if (nameA < nameB) return -1;
    return 0;
});

za_part.sort(function(a, b) {
    var nameA = a.first_name.toLowerCase();
    var nameB = b.first_name.toLowerCase();
    if (nameA > nameB) return -1;
    if (nameA < nameB) return 1;
    return 0;
});

Answer №1

The variables az_part, za_part, and participants all point to the same array in memory. You are first sorting the array in ascending order and then immediately re-sorting it in descending order.

To avoid this issue, use the slice method to create shallow copies of the array:

var az_part = participants.slice();
var za_part = participants.slice();

A shallow copy means that new arrays are created but the objects within them remain the same. If you make changes to an object in one array, it will reflect in all arrays containing that object. For example, participants[2].notes = "foo" will affect the object in each list.

Answer №2

When working with JavaScript objects, including arrays, it's important to remember that they are references to objects. This means that when you sort an array, you're actually sorting the original array itself, not a copy of it.

For a more detailed explanation of this concept, check out the following question.

Why does modifying an Array in JavaScript impact duplicates of the array?

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

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Discover the largest discrepancy by utilizing an array

#include <iostream> using std::cin; using std::cout; using std::endl; int main() { int num; long long max = 0; long long min; cin >> num; long long *ptr = new long long[num]; for (int x = 0; x < num; x++) { ...

What is the best way to perform this task in Angular2?

I am currently working with three arrays: tables = [{number:1},{number:2},{number:3},{number:4}]; foods = [ {id:1, name:'Ice Cream'}, {id:2, name:'Pizza'}, {id:1, name:'Hot Dog'}, {id:2, name:'Salad'} ]; o ...

Is there a way to locate all the indexes of a particular value within an array using PHP without the need for

Is there a method to retrieve all indexes of an array that contain a specific value, as opposed to just the first index returned by array_search()? I need to find all occurrences of a certain value in an array. How can this be achieved? For example, using ...

Creating an Array of Interfaces in SystemVerilog: A Step-by-Step Guide

I'm currently working on designing an interface that involves an array of a simpler interface. In VHDL, I would typically define two types, a record and an array of records. However, I am facing some challenges in achieving the same in SystemVerilog. ...

The useSelector value remains undefined within the handleSubmit button in a React component

Once a user fills out and submits the form, the action is triggered to call the API. Upon returning the postId, it is stored in the reducer. The main React component then utilizes useSelector to retrieve the latest state for the postId. However, when attem ...

JavaScript - Sort an array containing mixed data types into separate arrays based on data

If I have an array such as a=[1,3,4,{roll:3},7,8,{roll:2},9], how can I split it into two arrays with the following elements: b=[1,3,4,7,8,9] c=[{roll:3},{roll:2}]. What is the best way to separate the contents of the array? ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

Display a loading icon during the process of uploading files

I've created a multipart/form-data form that is targeted to an iframe. Check it out below: <form id="uploadForm" method="post" action="sample.jsp" name="uploadForm" enctype="multipart/form-data" target="fileUploadFrame"> <input type=" ...

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Using JavaScript to display a live data table on a website sourced from Firebase

I am trying to generate a table with data from Google Firebase in JavaScript, but for some reason the table is not being displayed. Below is the code I am using: <a href="#usertable" onclick="openLink(event,'usertable');tab1();" class="tabl ...

Utilizing Angular's web architecture involves nesting components and concealing them with the ng-hide directive

I'm currently working on an Angular 1.X application and have encountered a scenario where a component is shared across three different pages. Within the main component, there are several nested components but only two of them should be displayed on a ...

What steps should I take to ensure that elements beneath a div are made visible?

I've been working on a unique project to create a website with "hidden text" elements. One of the cool features I've developed is a circular div that follows my mouse cursor and flips all text below it using background-filter in both CSS and Jav ...

The functionality of three.js Raycaster appears to be dependent on the initial key frame of animation in every instance

In my current project, raycasting selection works perfectly fine for static meshes. However, when it comes to animated meshes, the ray selection seems to ignore the movement of the mesh and only recognizes the original position of the mesh. The issue aris ...

Is it necessary for me to install node and npm in order to use bower, even if I am not a node programmer?

As a Java programmer focusing on a web application, I'm finding that managing JavaScript can be quite challenging. I recently discovered Bower, a JavaScript dependency manager, but found out that it requires both Node and npm to be installed first. ...

A guide to parsing JSON files and extracting information

How can I extract the name and status from a JSON object? I've attempted various methods like [0] - [1], as well as trying without, but to no avail. [ { "status": "OK" }, { "id": "1" ...

Cannot use Object.keys function in AngularJS

For my UI.Bootstrap accordion, I have set up the heading as follows: <accordion-group ng=repeat="(cname, stations) in byClient"> <accordion-heading> {{ cname }} <span class="pull-right"> {{ Object.keys(stations).length }} Sta ...