How to sort strings in JavaScript

Asked
Active3 hr before
Viewed126 times

10 Answers

stringsjavascript
90%

x is equal to y: +(x > y) || -(x < y) -> 0 || 0 -> 0,x is larger than y: +(x > y) || -(x < y) -> 1 || 0 -> 1,x is smaller than y: +(x > y) || -(x < y) -> 0 || -1 -> -1,x is larger than y: (x > y) - (y < x) -> 1 - 0 -> 1

Use String.prototype.localeCompare a per your example:

list.sort(function(a, b) {
   return ('' + a.attr).localeCompare(b.attr);
})

We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:

if (item1.attr < item2.attr)
   return -1;
if (item1.attr > item2.attr)
   return 1;
return 0;
load more v
88%

Using sort() method: In this method, we use predefined sort() method of JavaScript to sort the array of string. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method.,We can sort the strings in JavaScript by following methods described below:,Using loop: We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array.Examples:,How to sort strings in JavaScript?

load more v
72%

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).,The sort() method sorts the elements of an array.,By default, the sort() method sorts the values as strings in alphabetical and ascending order.,sort() overwrites the original array.

Definition and Usage

The sort() method sorts the elements of an array.

sort()
load more v
65%

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. , The sorted array. Note that the array is sorted in place, and no copy is made. ,After sorting this array by grade in ascending order:, The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

// Functionless
sort()

// Arrow function
sort((firstEl, secondEl) => {
   ...
})

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(firstEl, secondEl) {
   ...
})
load more v
75%

Sorting String Letters In Alphabetical OrderBy Comparing ASCII codeBy Using Array.sort Method,Sorting String Letters In Alphabetical Order Using JavaScript,Problem : Sort String letters In Alphabetical Order,Approach : Comparing the ASCII code to sort the string letters using JavaScript

function sortString(str) {
   var arr = str.split('');
   var tmp;
   for (var i = 0; i < arr.length; i++) {
      for (var j = i + 1; j < arr.length; j++) {
         /* if ASCII code greater then swap the elements position*/
         if (arr[i] > arr[j]) {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
         }
      }
   }
   return arr.join('');
}
load more v
40%

On using sort() method, we are using a predefined method by JavaScript to sort array of strings.,Simple Sort string in JavaScript using sort() method,Here we have taken an array of strings, these are sorted using the sort() method in alphabetical order by default.,sort() method returns array after sorting the elements of the array.

As said, the sort() method sorts elements with the smallest value at the start and largest at last.

<array_name>.sort();

<array_name>.sort();
load more v
22%

Sorting Mixed Case Strings , Unicode Values for Characters , Attempt One: Without a Comparison Function , Attempt Two: With a Comparison Function

We’ll start by creating utility functions that helps get the unicode values of characters as well as the characters. We will refer to them as we go.

// get Unicode values of character items in an array
function getCharactersUnicodeValue(characters) {
   const unicodeChart = new Map();
   characters.forEach(character => {
      unicodeChart.set(
         character,
         character.charCodeAt(character.indexOf(character))
      );
   });
   console.table(unicodeChart);
}

// get unicode values of a single character
function getCharacterUnicodeValue(character) {
   const value = character.charCodeAt(character.indexOf(character));
   console.log(value);
}
load more v
60%

In this tutorial, you have learned how to use the JavaScript Array sort() method to sort arrays of strings, numbers, dates, and objects.,Summary: in this tutorial, you will learn how to use the JavaScript Array sort() method to sort arrays of numbers, string, and objects.,Therefore, to sort employees by hire date, you first have to create a valid Date object from the date string, and then compare two dates, which is the same as comparing two numbers.,This example is similar to the example of sorting an array of numbers in ascending order. The difference is that it compares the salary property of two objects instead.

Consider the following example:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort();
console.log(numbers);
Code language: JavaScript(javascript)
load more v
48%

In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. ,To sort the elements of the animals array in ascending order alphabetically, we need to use the sort( ) method without passing the compare function as in the example: ,Sorting Arrays of Strings Let's practice with an array of string named animals, as follows: ,Also, note that the sort( ) method accepts two arguments and will return a value that determines the sort order, the following represents the syntax:

Array.sort([comparer])
load more v
23%

users.sort((a, b) => a.firstname.localeCompare(b.firstname))
load more v

Other "strings-javascript" queries related to "How to sort strings in JavaScript"