Basic usage and pitfalls of JavaScript array sort() method

Basic usage and pitfalls of JavaScript array sort() method

Preface

In daily code development, there are many operations related to array sorting. In JavaScript, you can call the sort method to quickly sort the array.

Today, let’s learn about the sort method of arrays to avoid the tragic experience of stepping into pitfalls in the future.

concept

The sort method is used to sort the elements of an array.

grammar

arr.sort([compareFunction])

Parameter parsing

compareFunction (optional)

A function used to specify a certain order of arrangement. This function takes two parameters:

  • firstEl The first element to be compared
  • secondEl The second element to be compared

If this function is omitted, the elements are sorted according to the Unicode positions of the characters in the converted string.

Return Value

The sorted array.

Note that the array is sorted in-place and no copies are made.

sort method source code

DEFINE_METHOD(
  GlobalArray.prototype,
  sort(comparefn) {
    CHECK_OBJECT_COERCIBLE(this, "Array.prototype.sort");

    if (!IS_UNDEFINED(comparefn) && !IS_CALLABLE(comparefn)) {
      throw %make_type_error(kBadSortComparisonFunction, comparefn);
    }

    var array = TO_OBJECT(this);
    var length = TO_LENGTH(array.length);
    return InnerArraySort(array, length, comparefn);
  }
);

This step shows that the sort method calls the InnerArraySort method, and the parameters are the array, the array length, and the comparison function. Let's take a look at how the InnerArraySort method handles this.

pit

I still remember the first time I used array sorting: I found a sort method and used it immediately. The result was as follows:

const arr = [49, 5, 14, 89, 71, 3, 10];
arr.sort();
// Output [10, 14, 3, 49, 5, 71, 89]

The moment I saw the result, I was a little shocked.

This is a bit unethical. Where is the agreed order? After confirming that there was nothing wrong with my machine, I quickly checked the documentation to see what it said:

If compareFunction is not specified, then the elements are sorted according to the character-by-character Unicode positions of the converted strings.

With this explanation, the sorting of the above array can be understood as follows:

First, convert the numbers in the array into strings one by one and get ['49', '5', '14', '89', '71', '3', '10'].

If we calculate according to the Unicode position of the first character:

  • 1 is encoded before 3, so 10 and 14 are ranked before 3.
  • 3 is encoded before 4, so 49 comes after 3...

If the codes of the first characters are the same, the codes of the second characters are compared. For example, 10 comes before 14 (the comparison result of 0 and 4).

The logic seems to make sense, but this is not the result I want. It seems that I still have to rely on the comparison function compareFunction. Let's take a look at what this compareFunction is.

usage

The basic use case is as follows:

const arr = [49, 5, 14, 89, 71, 3, 10];

// General way to write arr.sort(function (a, b) {
    return a - b; // sort in ascending order });

// Arrow function arr.sort((a, b) => a - b);

// Result [3, 5, 10, 14, 49, 71, 89]

The above is the way to sort in ascending order. If you want to sort in descending order, just change return a - b; in the comparison function to return b - a;.

Sorting an array of objects

In addition to sorting numeric and character arrays, the sort() method can also be used to sort object arrays:

var items = [
    {name: 'Edward', value: 21},
    {name: 'Sharpe', value: 37},
    {name: 'And', value: 45},
    {name: 'The', value: -12},
    {name: 'Magnetic'},
    {name: 'Zeros', value: 37}
];

// sort by value
items.sort(function (a, b) {
    return (a.value - b.value)
});

// sort by name
items.sort(function (a, b) {
    var nameA = a.name.toUpperCase(); // ignore upper and lowercase
    var nameB = b.name.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        return -1;
    }
    if (nameA > nameB) {
        return 1;
    }

    // names must be equal
    return 0;
});

Sorting non-ASCII characters

When sorting strings containing non-ASCII characters (such as strings containing characters like e, é, è, a, ä, etc.). Some non-English language strings require the use of

var items = ['reservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
	return a.localeCompare(b);
});

// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']

Using mapping to improve sorting

The compareFunction may need to map the elements multiple times to achieve sorting. Especially when the compareFunction is complex and there are many elements, some compareFunctions may cause high load. It would be a good idea to use a map to assist in sorting. The basic idea is to first take out the actual value of each element in the array, sort it, and then restore the array.

// Array to be sorted var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];

// Temporary storage for numbers and positions that need to be sorted var mapped = list.map(function(el, i) {
  	return { index: i, value: el.toLowerCase() };
})

// Sort array by multiple values ​​mapped.sort(function(a, b) {
  	return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// Get the sorted result according to the index var result = mapped.map(function(el){
  	return list[el.index];
});

Summarize

This concludes this article about the basic usage of the array sort() method in JavaScript. For more information on the usage of the JavaScript array sort() method, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Introduction to Js array sorting function sort()
  • Javascript array sorting sort() method and reverse() method
  • Detailed explanation of Array.sort() sorting method in JavaScript
  • js uses Array.prototype.sort() to sort array objects
  • Fast cloning of JavaScript arrays (slice() function) and sorting, shuffling, and searching of arrays (sort() function)
  • Sorting array elements using the sort() method in JavaScript
  • Detailed explanation of javascript sort() to sort the elements in an array
  • Introduction to the use of the sort() method of arrays in javascript
  • JavaScript array sorting reverse() and sort() methods explained in detail

<<:  win10 docker-toolsbox tutorial on building a php development environment

>>:  MySQL 8.0.15 installation and configuration method graphic tutorial under Windows

Recommend

Ubuntu 20.04 Best Configuration Guide (Newbie Essential)

1. System Configuration 1. Turn off sudo password...

Detailed explanation of Vue plugin

Summarize This article ends here. I hope it can b...

Some wonderful uses of URL objects in JavaScript

Table of contents Preface Parsing parameters Modi...

Why is IE6 used by the most people?

First and foremost, I am a web designer. To be mor...

Detailed explanation of formatting numbers in MySQL

Recently, due to work needs, I need to format num...

HTML thead tag definition and usage detailed introduction

Copy code The code is as follows: <thead> &...

CSS uses radial-gradient to implement coupon styles

This article will introduce how to use radial-gra...

MySQL 8.0.20 installation and configuration method graphic tutorial

MySQL download and installation (version 8.0.20) ...

WeChat applet calculator example

WeChat applet calculator example, for your refere...

Example of converting JS one-dimensional array into three-dimensional array

Today I saw a friend asking a question in the Q&a...

Simple summary of tomcat performance optimization methods

Tomcat itself optimization Tomcat Memory Optimiza...