The use of the sort function in the Array built-in object in JavaScript

1. Concept

        The sort() method sorts the elements of an array and returns an array sorted according to the specified requirements. The default sort order is to compare elements after converting them to strings.

2. Grammar

        arr.sort( compareCallback( firstElement, secondElement ) )

illustrate:

        compareCallback( firstElement, secondElement ) is a comparison callback function passed to sort(), which is used to specify a function to be arranged in a custom order. When not passed, the elements are sorted according to the Unicode position of each character in the converted string.

        firstElement The first element to compare.

        secondElement The second element to compare.

        When compareCallback( firstElement, secondElement ) is less than 0, ascending order

        When compareCallback( firstElement, secondElement ) is equal to 0, the position remains unchanged

        When compareCallback( firstElement, secondElement ) is greater than 0, descending order

3. Example

1. Comparing arrays of numbers

let numArr = [ 12, 32, 11, 45, 7, 0, 28 ]

let sortedNumArr1 = numArr.sort()

console.log( sortedNumArr1 ) // output result: [0, 11, 12, 28, 32, 45, 7] // sorting error

When the default sorting is used to arrange the number array above, the elements are converted into strings for comparison, so sorting errors will occur .

let sortedNumArr2 = numArr.sort( ( first, second ) => first - second )

console.log( sortedNumArr2 ) // output: [0, 11, 12, 28, 32, 45, 7] // sorted correctly

2. Compare string arrays

let strArr = ['LinLiu', 'HuangWu', 'ZhaoQi', 'zhongli', 'a']

let sortedStrArr1 = strArr .sort()

console.log( sortedStrArr1 ) // output result: ['HuangWu', 'LinLiu', 'ZhaoQi', 'a', 'zhongli']

Ignore case comparison

let sortedStrArr2 = strArr .sort(( first, second ) => {

        // Uniformly convert to uppercase for comparison

        let firstName = first.toUpperCase()

        let secondName = second .toUpperCase()

        if ( firstName < secondName  ) return -1

        if ( firstName > secondName  ) return 1

        return 0

} )

console.log( sortedStrArr2 ) // output result: ['a', 'HuangWu', 'LinLiu', 'ZhaoQi', 'zhongli']

Guess you like

Origin blog.csdn.net/my__flower/article/details/122087026