"Prior to executing the sort function, the JavaScript array undergoes a

Update: It seems like the issue is related to how the chrome console handles object evaluation, as pointed out by jsN00b.

original source

I am currently sorting an array by name and then by age, and logging the array three times: First right after initialization, Second and third times are after sorting the array by name and then age respectively.

However, the first console.log() call displays the array in its sorted state, whereas I was expecting it to show the array in its unsorted state.

Not sure if this behavior is due to the way JavaScript manages arrays in memory or if it's a bug?

Code:

function byField(field) {
  return (objA, objB) => (objA[field] > objB[field] ? 1 : -1);
}

let users = [
  { name: "John", age: 20, surname: "Johnson" },
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
];

console.log(users);
users.sort(byField("name"));
console.log(users);
users.sort(byField("age"));
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Expected output:

//unsorted
[
  { name: "John", age: 20, surname: "Johnson" },
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
];

//by name
[
  { name: "Ann", age: 19, surname: "Hathaway" },
  { name: "John", age: 20, surname: "Johnson" },
  { name: "Pete", age: 18, surname: "Peterson" },
];

//by age
[
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
  { name: "John", age: 20, surname: "Johnson" },
];

Actual Output:

//unsorted
[
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
  { name: "John", age: 20, surname: "Johnson" },
];

//by name
[
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
  { name: "John", age: 20, surname: "Johnson" },
];

//by age
[
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" },
  { name: "John", age: 20, surname: "Johnson" },
];

Answer №1

The built-in method Array.prototype.sort will alter the original array. To avoid this, you should create a copy of the array and then sort the copy instead. Here is an example that demonstrates this concept:

[...customers].sort(byAttribute("name"));

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

Boost the frequency of updates in Meteor.observe

When Python writes to a database (mongo) every second in the setup, Meteor.js is expected to react immediately to the new record insertion. Issue: However, the use of cursor.observe() results in the console outputting only 4-5 seconds after the new record ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Using Ajax to poll a Celery task

I am working on a Celery task that updates a PostgreSQL database gradually. In my Django application, I want to fetch the latest data from the database and display it in a template in real-time as the task progresses. I am looking to implement this real-ti ...

What is the process for displaying the index of an array element on the console once the highest and lowest ranges have been determined?

I'm having trouble identifying the longest and shortest 'Track' number that was calculated. I don't know what to call this particular value. Right now, my program is only returning 0, which was the initial value for both calculations. A ...

Tips for adding/removing items in arrays using Ember.js

Is it possible to modify an array within an Ember object using methods like push and pop while still keeping the UI bindings updated? While I can easily display the contents of an array in an Ember object using Handlebars, making changes directly to the ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Having trouble determining the offsetHeight of an element within AngularJS

My directive, named 'myObject', is supposed to log the offsetHeight of its target element. However, it's not working as expected. I suspect it's because the height is being calculated before the element has any content. Is there a solu ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

What is the method for performing a spelling check on every property within an array of Objects?

I'm working on a program that takes a user input as an argument and then searches for a similar match in an array of objects. The array of objects is retrieved from a database. When the user inputs a name, the search criteria should find objects with ...

Updating information dynamically in a controller based on an ng-repeat from a different controller in AngularJS

To enhance comprehension, I've created a straightforward example. For this scenario, ng-repeat is used to call a template that has its own controller. However, the controller of the template requires injected data from a service for each ng-repeat it ...

Error: The AJAX request encountered an unexpected token in the JSON response

I am working with the following code snippet: $.ajax({ dataType: 'text', url: '/_/js/answers.json', type: "GET", success: function (data) { alert(data); ...

Using the power of jQuery to create straightforward CSS animations

On my simple webpage, I have a main content area called content-wrapper and a sidebar on the right side named #sidebar-right I am attempting to create a margin on the right side of the content to prevent it from overlapping the sidebar, and have it expand ...

Using Ajax to Trigger Firebase Functions in Node.js - A 408 Error

I've been diving into the world of Firebase and recently started experimenting with Firebase functions by referring to the official documentation. From what I gathered, Firebase functions essentially allow you to write Node.js code that operates as a ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

Names picked at random and presented in the innerHTML

I am currently working on a project that involves displaying random names from an array in a text area named "textbox". Currently, I am using math.random() to pick a name randomly, but it only generates a new random name when the page is reloaded. How ca ...

Angular does not automatically add a class

My Angular function looks like this: $scope.show = function(el){ if($scope.steps[el] == true){ $scope.steps[el] = false; } else{ $scope.steps = []; $scope.steps[el] = true; } } When I trigger it by clicking on thi ...

Troubleshooting issue with Bootstrap's responsive scrollspy functionality

I am experiencing an issue with the responsiveness of my page. When I reduce the width of the page to half, the scrollspy disappears unexpectedly. I am unsure about the root cause of this problem. If you run the code I have shared here, you can observe th ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...