js array sorting, the array is sorted in the forward and reverse order of a certain field, sort()

Not much to say, just look at the case.
For example, if the backend returns an array collection, you need to put the default option in the first item.

let arr = [
      {
    
    isDefault: 0},
      {
    
    isDefault: 0},
      {
    
    isDefault: 1},
      {
    
    isDefault: 0}
    ]
    arr.sort((a,b)=> a.isDefault-b.isDefault)
    console.log(arr,'正序')

Output result: positive sequence, sorted from small to large
insert image description here

    arr.sort((a,b)=> b.isDefault-a.isDefault)
    console.log(arr,'倒序')

Output result: reverse order, sorted from large to small The
insert image description here
above is the data result of the object contained in the processed array, of course, it is also very convenient to process some other types of array data,
such as processing letter type arrays:

 let arr = [
      'a','c','d','b'
    ]
    arr.sort();
    console.log(arr) //  ['a', 'b', 'c', 'd']

Number type:

let arr = [
      2, 4, 1, 3
    ]
    arr.sort();
    console.log(arr) // [1, 2, 3, 4]

Guess you like

Origin blog.csdn.net/m0_46156566/article/details/127747894