What is causing the issue with Array.prototype.sort() not functioning properly in Chrome's development tool?

const array = [{name:'Suzanne'},{name:'Jim'},{name:'Trevor'},{name:'Amanda'}];

array.sort((a,b)=>a.name > b.name);

I am attempting to sort the objects in my array alphabetically by name, from A to Z. The code works perfectly when executed in node(v8.4.0) and Safari's development console.

However, there seems to be an issue with getting it to work in Chrome's development console (v70.0.3538.110). When I try to run the code in Chrome, the result is not as expected.

As far as I can tell, the code itself should be correct. I'm unsure why it's not functioning correctly in Chrome and would appreciate any insight into this matter.

Answer №1

The .sort() function must return a number, not a boolean. The outcome should be:

  • a negative number to place the first element before the second;
  • a positive number to place the first element after the second;
  • zero if both elements are in the same order.

When dealing with strings, you can utilize the .localeCompare() method like so:

arr.sort((a,b) => a.name.localeCompare(b.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

Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message Class constructor XX cannot be invoked without 'new'. After researching online, it seems that this problem typically arises when a transpiled cla ...

Sending JSON data from a Django view to a JavaScript function

I am trying to pass JSON data to JavaScript. I need the JSON structure to be like this: data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database ...

How can I change the behavior of the Enter key in text fields to automatically submit the form, rather than requiring the user to

Utilizing material UI for my component library, I have a compact dialog with a "recover password" button placed within the form. However, upon adding this button, I noticed that pressing the "enter" key in the text fields triggers the onClick event of the ...

Tips for utilizing the value of object1.property as a property for object2

Within the template of my angular component, I am attempting to accomplish the following: <div> {{object1.some_property.(get value from object2.property and use it here, as it is a property of object1)}} </div> Is there a way to achieve this ...

How to remove an inner child node in JSON efficiently without disrupting the structure

Trying to use jq to eliminate a specific node from a JSON file. The structure of the JSON file is as follows: { "etag": "14b3796c268c87553291702c808e86dfe1e53d1b", "rules": { "name": "default", "children": [ { "name": "xxxx", ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

External JavaScript functions remain hidden from the HTML page

Having issues with JavaScript functions. I created functions in a separate file named index.js, but when I use them in index.html like "onclick = function()", the file doesn't recognize the function. <!doctype html> <html lang="{{ app()-> ...

Issue with TypeORM: The database table is not being created during migration execution in the SQLITE environment

I'm currently encountering an issue with utilizing migrations in TypeORM with a sqlite3 database. My goal is to achieve consistency across different environments (local/testing/staging/production) by only using runtime environment variables that will ...

Array of Checkboxes

Seeking assistance with a coding dilemma. Here is the existing code snippet: <section> <span class="tags"></span> <label for="shoes">Shoes</label> <input type="checkbox" id="shoes"> <label for="jeans">Je ...

Guide to populating a dynamic dropdown menu by utilizing the formArray index when making a selection

I'm facing a situation where I need to add/remove form groups with multiple form controls. Let's consider this scenario: https://i.sstatic.net/N2HhL.png The first dropdown represents the country list, the second dropdown displays states based ...

"The Promise in the AngularJS Karma test specification did not resolve and the .then() method was not invoked

An issue arises when attempting to perform AngularJS Karma Unit Testing on a service. The service includes a method like the one below: service.getIntersectingElements = function (element, elements) { var deferred = $q.defer(); var tolerance = 20 ...

Iterate through the pixels of the canvas to locate the x and y coordinates and position of each white pixel

In my project, I have a canvas with white text drawn on it. To identify the white pixels, I extract the image data and iterate through each pixel using the following code snippet: var pixelData = this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx ...

What is the best way to use JavaScript to conceal all div elements?

Can someone please provide a JavaScript solution to hide all divs on a web page without using jQuery? I am looking for a method that does not involve using the arrays that are associated with document.getElementByTag. If this is not possible, could you p ...

Utilize AngularJS to efficiently filter an array based on selections made in a combobox

I have experience filtering an array using an input text as the filter. However, I am curious if it is possible to utilize the filter property of AngularJS with a combobox as the filter options. For instance, imagine I have an array of years: [2014,2014,2 ...

Having trouble with managing state changes in a React application using Multiple Checkbox components from M

Trying to update the state of multiple checkboxes and then send a POST request. Visually, the checkboxes change, but the form data remains unchanged. Here is the code snippet: export default function AccountInformations(props) { // const { enqueueSnack ...

Incorporate SWFAddress.js into your Flex project for added functionality

Is there a method to set up my Flex 4 project so that it incorporates the JavaScript aspect of the SWFAddress library? I have successfully integrated the AS, but currently, in order to test how it works, I need to open Main.html and include swfaddress.js e ...

The popup is unable to remain in the center of the screen because the background page keeps scrolling back to the top

Whenever I click a button to open a popup window, the page unexpectedly scrolls to the top. It's frustrating because if I'm at the bottom of the page and press the 'submit' button, the popup doesn't display in the center as intende ...

Creating a smooth transition effect for a welcoming message using PHP upon logging in

In the given code snippet for setting a cookie on a website, the logic is such that it checks if the cookie with user's full name already exists. If it does, it immediately displays a welcome message to the user and redirects them to the home page aft ...

Add zeros to the beginning of a one-dimensional column vector

What is the process for converting a 1D numpy array into a 2D numpy array and filling the columns with zeroes? For instance: Input: a = np.array([1,2,3]) Desired output: np.array([[0, 0, 1], [0, 0, 2], [0, 0, 3]]) Could you explai ...

Creating copies of list elements within an array using R

Greetings to all members of this forum and R community! As a newcomer, I ask for your understanding if my query lacks clarity or inadvertently violates any forum norms. Currently, I am engaged in a simulation study using R, implementing a 'for' ...