This is the 8th day of my participation in Gwen Challenge

In the daily code development, the operation of array sort can be many, JavaScript can call the sort method to sort the array quickly.

Today, the array sort method to learn, to avoid the sad experience of the future.

concept

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

grammar

arr.sort([compareFunction])
Copy the code

Argument parsing

CompareFunction (optional)

Used to specify functions that are sorted in a certain order. This function takes two arguments:

  • FirstEl is the first element to compare
  • SecondEl The second comparison element

If omitted, elements are sorted by the Unicode loci of each character in the converted string.

The return value

Sorted array.

Note that the array is sorted in place and is not copied.

pit

I remember the first time I used array sort: when I found a sort method, I used it. That is as follows:

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

When I saw the result, I was a little more generous.

This is a little bit not to talk about martial virtue, said the good sort? After double-checking that there is nothing wrong with my machine, check the documentation to see what it says:

If compareFunction is not specified, the element is sorted according to the character-by-character Unicode point of the converted string.

The order of the array above can be interpreted as follows:

  1. First of all, will be number one by one into a string array, get [‘ 49 ‘, ‘5’, ’14’, ’89’, ’71’, ‘3’, ’10’].

  2. Using the Unicode site of the first character:

    • 1 comes before 3, so 10 and 14 come before 3

    • 3 comes before 4, so 49 comes after 3

    If the encoding of the first character is the same, the encoding of the second character is compared, for example, 10 is ranked before 14 (comparison of 0 and 4).

CompareFunction = compareFunction = function compareFunction = function compareFunction = function compareFunction

usage

Basic use for example:

const arr = [49.5.14.89.71.3.10];

//
arr.sort(function (a, b) {
    return a - b;   // In ascending order
});

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

// Results [3, 5, 10, 14, 49, 71, 89]
Copy the code

Return a – b; return a – b; return a – b; Return b – a; .

Object array sort

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;
});
Copy the code

Sort non-ASCII characters

When sorting non-ASCII characters (such as strings containing characters like E, E, e, a, a, etc.) Some strings in non-English languages require string.localecompare. This function sorts functions into the correct order.

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

/ / the items is [' adieu ', 'cafe', 'cliche', 'communique', 'premier', 'reserve']
Copy the code

Use maps to improve sorting

Comparefunctions may need to map elements multiple times to achieve sorting, especially if comparefunctions are complex and have many elements, some comparefunctions can be very heavy. It would be a good idea to use Map-assisted sorting. The basic idea is to first extract the actual value for each element in the array, sort it, and then restore the array.

// The array to be sorted
var list = ['Delta'.'alpha'.'CHARLIE'.'bravo'];

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

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

// Get the sort result by index
var result = mapped.map(function(el){
  	return list[el.index];
});
Copy the code

This article is over, thanks for reading!

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Everybody is good! I am the author of programming Samadhi, yi Wang, my public account is “programming Samadhi”, welcome to pay attention to, I hope you can give me more advice!

Knowledge and skills should be paid equal attention to, internal force and external power should be repaired simultaneously, theory and practice should grasp both hands, both hands should be hard!

~