Skip to content
Fix Code Error

Sort array by firstname (alphabetically) in Javascript

March 13, 2021 by Code Error
Posted By: Anonymous

I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript.
How can I do it?

var user = {
   bio: null,
   email:  "[email protected]",
   firstname: "Anna",
   id: 318,
   lastAvatar: null,
   lastMessage: null,
   lastname: "Nickson",
   nickname: "anny"
};

Solution

Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator)

It should return

  • something negative if first argument is less than second (should be placed before the second in resulting array)
  • something positive if first argument is greater (should be placed after second one)
  • 0 if those two elements are equal.

In our case if two elements are a and b we want to compare a.firstname and b.firstname

Example:

users.sort(function(a, b){
    if(a.firstname < b.firstname) { return -1; }
    if(a.firstname > b.firstname) { return 1; }
    return 0;
})

This code is going to work with any type.

Note that in “real life”™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare. See other answers for clarity.

Answered By: Anonymous

Related Articles

  • Combining Ember Table with Ember Data
  • How to filter a RecyclerView with a SearchView
  • Backbone collection comparator
  • Polymer 1.0 strange behaviour on properties
  • Problems Installing CRA & NextJS from NPM…
  • LINQ search on multiple columns and determine on…
  • display js variable to html using vue js
  • GLYPHICONS - bootstrap icon font hex value
  • Sorting Backbone Collections
  • HQL Responding with…
  • correctly implement backbone comparators
  • What is the difference between compare() and compareTo()?
  • Use of PUT vs PATCH methods in REST API real life scenarios
  • Collections sort(List,Comparator
  • Backbone.js Comparator not sorting (Coffeescript)
  • Convert pem key to ssh-rsa format
  • org.hibernate.hql.internal.ast.QuerySyntaxException:…
  • Vue.js - How to implement Computed properties on…
  • Laravel 5.2 Missing required parameters for [Route:…
  • Proper way to sort a backbone.js collection on the fly
  • My quick Sort Function in Kotlin give the wrong output back
  • Sort ArrayList of custom Objects by property
  • Excel: Generating Months Data from Start and End Date
  • Pandas-way to separate a DataFrame based on…
  • javascript .replace and .trim not working in vuejs
  • Sorting an ArrayList of objects using a custom sorting order
  • Getting an object array from an Angular service
  • Rails wrong number of arguments error when…
  • Javascript dynamic sorting array of object include…
  • Spring Data JPA Update @Query not updating?
  • Postgres: How to update multiple records in a table…
  • Using curl POST with variables defined in bash…
  • Append to tbody using AJAX call
  • The definitive guide to form-based website authentication
  • Stop collection from sorting itself but still able to sort i
  • Implement Firebase simpleLogin email & password…
  • How can I use optional parameters in a T-SQL stored…
  • How can I replace specific strings within an object?
  • Java : Comparable vs Comparator
  • What is the cause of the "route not defined" error…
  • Typeerror: n is undefined in underscore.min.js
  • Does Python have a toString() equivalent, and can I…
  • ASP.NET MVC - Set custom IIdentity or IPrincipal
  • How to reduce compilation time by using for loop
  • Java 8 stream's .min() and .max(): why does this compile?
  • How to perform stable sort in C++ when using a…
  • backbone.js: Update model, re-sort and re-render…
  • Reading json files in C++
  • How to implement a multi-level sort in comparator in…
  • Sorting using Comparator- Descending order (User…
  • Formik form only validates after second button…
  • TypeScript metadata reflection references other…
  • SQL update statement in C#
  • Making a pop up template in Ember.js
  • What's wrong with 'template int compare(char p1 [N],…
  • In Aurelia computeds, when setting dependencies, how…
  • SwiftUI View Not Updating on Button Toggle After…
  • limited input from user in struct
  • Get specific data from vuex store while using a route
  • Removing double quotes from variables in batch file…
  • How do I use a PriorityQueue?
  • What is “2's Complement”?
  • Detect whether a Python string is a number or a letter
  • Java class object in Kotlin
  • Vuetify checkboxes array checks all boxes when list changes
  • Python 3 - ValueError: not enough values to unpack…
  • Hidden property of a button in HTML
  • Backbone.js filter on any value in a collection
  • Mock MVC - Add Request Parameter to test
  • Adding numbers and receiving a NaN
  • LINQ - Full Outer Join
  • How to send file by email from Firebase Storage…
  • What does this symbol mean in JavaScript?
  • Ember link-to handlebars and jQuery DataTables
  • State hooks does not update state parameters on…
  • Smart way to truncate long strings
  • Overriding Backbone.js comparator
  • What are the undocumented features and limitations…
  • How to speed up for loop in R
  • Why does C++ code for testing the Collatz conjecture…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How do I update an entity using spring-data-jpa?
  • T-SQL: Can I query one view for values and then…
  • How to catch form submit with Backbone.js
  • How to sort an array of objects in Java?
  • How to use the encrypt password for login php
  • Using less in a polymer-dart application
  • How do I get multiple data from another page?
  • Vue2: Init data with other data value
  • How can I configure Storybook.js Webpack with…
  • Java Comparator class to sort arrays
  • Vuetify form validation errors after reset
  • For-each over an array in JavaScript
  • How to POST the data from a modal form of Bootstrap?
  • Java : Sort integer array without using Arrays.sort()
  • Sort table rows In Bootstrap
  • Sorting strings in reverse order with backbone.js
  • Vuejs: Show error messages as popups
  • No Spring WebApplicationInitializer types detected…
  • Change multiple SVG paths in CSS on hover or with javaScript

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to convert a Map to List in Java?

Next Post:

Get month and year from a datetime in SQL Server 2005

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error