Hướng dẫn javascript sort value - giá trị sắp xếp javascript

Phương thức

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 sắp xếp các phần tử của một mảng tại chỗ và trả về tham chiếu đến cùng một mảng, hiện được sắp xếp. Thứ tự sắp xếp mặc định là tăng dần, được xây dựng khi chuyển đổi các yếu tố thành các chuỗi, sau đó so sánh các chuỗi các giá trị đơn vị mã UTF-16 của chúng.
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7
method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Độ phức tạp về thời gian và không gian của loại không thể được đảm bảo vì nó phụ thuộc vào việc thực hiện.

Thử nó

Cú pháp

// Functionless
sort()

// Arrow function
sort((a, b) => { /* … */ } )

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(a, b) { /* … */ })

Thông số

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 Tùy chọnOptional

Chỉ định một hàm xác định thứ tự sắp xếp. Nếu bị bỏ qua, các phần tử mảng được chuyển đổi thành các chuỗi, sau đó được sắp xếp theo giá trị điểm mã Unicode của mỗi ký tự.

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9

Yếu tố đầu tiên để so sánh.

function compareNumbers(a, b) {
  return a - b;
}
0

Yếu tố thứ hai để so sánh.

Giá trị trả về

Các tham chiếu đến mảng ban đầu, bây giờ được sắp xếp. Lưu ý rằng mảng được sắp xếp tại chỗ và không có bản sao nào được thực hiện.

Sự mô tả

Nếu

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 không được cung cấp, tất cả các phần tử không phải là -____ 22 được sắp xếp bằng cách chuyển đổi chúng thành các chuỗi và so sánh các chuỗi theo thứ tự đơn vị mã UTF-16. Ví dụ: "chuối" đến trước "anh đào". Trong một loại số, 9 đến trước 80, nhưng vì các số được chuyển đổi thành chuỗi, "80" xuất hiện trước "9" theo thứ tự Unicode. Tất cả các phần tử
function compareNumbers(a, b) {
  return a - b;
}
2 được sắp xếp đến cuối mảng.

Phương pháp

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 bảo tồn các khe trống. Nếu mảng nguồn thưa thớt, các khe trống được di chuyển đến cuối mảng và luôn luôn đến sau tất cả
function compareNumbers(a, b) {
  return a - b;
}
2.

Lưu ý: Trong UTF -16, các ký tự Unicode ở trên

function compareNumbers(a, b) {
  return a - b;
}
6 được mã hóa dưới dạng hai đơn vị mã thay thế, của phạm vi
function compareNumbers(a, b) {
  return a - b;
}
7 - ​​
function compareNumbers(a, b) {
  return a - b;
}
8. Giá trị của mỗi đơn vị mã được đưa riêng biệt để so sánh. Do đó, ký tự được hình thành bởi cặp thay thế
function compareNumbers(a, b) {
  return a - b;
}
9 sẽ được sắp xếp trước ký tự
const stringArray = ['Blue', 'Humpback', 'Beluga'];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ['80', '9', '700'];
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
0.
In UTF-16, Unicode characters above
function compareNumbers(a, b) {
  return a - b;
}
6 are encoded as two surrogate code units, of the range
function compareNumbers(a, b) {
  return a - b;
}
7 -
function compareNumbers(a, b) {
  return a - b;
}
8. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair
function compareNumbers(a, b) {
  return a - b;
}
9 will be sorted before the character
const stringArray = ['Blue', 'Humpback', 'Beluga'];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ['80', '9', '700'];
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
0.

Nếu

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 được cung cấp, tất cả các phần tử mảng không phải là -____ 22 được sắp xếp theo giá trị trả về của hàm so sánh (tất cả các phần tử
function compareNumbers(a, b) {
  return a - b;
}
2 được sắp xếp đến cuối mảng, không có lệnh gọi đến
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8).

const stringArray = ['Blue', 'Humpback', 'Beluga'];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ['80', '9', '700'];
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
5 Giá trị trả về
thứ tự sắp xếp
> 0Sắp xếp
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9 sau
function compareNumbers(a, b) {
  return a - b;
}
0
< 0 Sắp xếp
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9 trước
function compareNumbers(a, b) {
  return a - b;
}
0
=== 0Giữ thứ tự ban đầu của
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9 và
function compareNumbers(a, b) {
  return a - b;
}
0

Vì vậy, hàm so sánh có dạng sau:

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

Chính thức hơn, bộ so sánh dự kiến ​​sẽ có các thuộc tính sau, để đảm bảo hành vi sắp xếp thích hợp:

  • Tinh khiết: Bộ so sánh không làm biến đổi các đối tượng được so sánh hoặc bất kỳ trạng thái bên ngoài nào. .
  • Ổn định: Bộ so sánh trả về kết quả tương tự với cùng một cặp đầu vào.
  • Phản xạ:
    const items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];
    
    // sort by value
    items.sort((a, b) => a.value - b.value);
    
    // sort by name
    items.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // names must be equal
      return 0;
    });
    
    2.
  • Anti-symetric:
    const stringArray = ['Blue', 'Humpback', 'Beluga'];
    const numberArray = [40, 1, 5, 200];
    const numericStringArray = ['80', '9', '700'];
    const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
    
    function compareNumbers(a, b) {
      return a - b;
    }
    
    stringArray.join(); // 'Blue,Humpback,Beluga'
    stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']
    
    numberArray.join(); // '40,1,5,200'
    numberArray.sort(); // [1, 200, 40, 5]
    numberArray.sort(compareNumbers); // [1, 5, 40, 200]
    
    numericStringArray.join(); // '80,9,700'
    numericStringArray.sort(); // ['700', '80', '9']
    numericStringArray.sort(compareNumbers); // ['9', '80', '700']
    
    mixedNumericArray.join(); // '80,9,700,40,1,5,200'
    mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
    mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
    
    5 và
    const items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];
    
    // sort by value
    items.sort((a, b) => a.value - b.value);
    
    // sort by name
    items.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // names must be equal
      return 0;
    });
    
    4 phải là
    const items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];
    
    // sort by value
    items.sort((a, b) => a.value - b.value);
    
    // sort by name
    items.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // names must be equal
      return 0;
    });
    
    5 hoặc có các dấu hiệu ngược lại.
  • Transitive: Nếu
    const stringArray = ['Blue', 'Humpback', 'Beluga'];
    const numberArray = [40, 1, 5, 200];
    const numericStringArray = ['80', '9', '700'];
    const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
    
    function compareNumbers(a, b) {
      return a - b;
    }
    
    stringArray.join(); // 'Blue,Humpback,Beluga'
    stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']
    
    numberArray.join(); // '40,1,5,200'
    numberArray.sort(); // [1, 200, 40, 5]
    numberArray.sort(compareNumbers); // [1, 5, 40, 200]
    
    numericStringArray.join(); // '80,9,700'
    numericStringArray.sort(); // ['700', '80', '9']
    numericStringArray.sort(compareNumbers); // ['9', '80', '700']
    
    mixedNumericArray.join(); // '80,9,700,40,1,5,200'
    mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
    mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
    
    5 và
    const items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];
    
    // sort by value
    items.sort((a, b) => a.value - b.value);
    
    // sort by name
    items.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // names must be equal
      return 0;
    });
    
    7 cả hai đều dương, bằng không hoặc âm, thì
    const items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];
    
    // sort by value
    items.sort((a, b) => a.value - b.value);
    
    // sort by name
    items.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // names must be equal
      return 0;
    });
    
    8 có tính tích cực giống như hai trước đó.

Một bộ so sánh phù hợp với các ràng buộc ở trên sẽ luôn có thể trả lại tất cả các

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

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
9,
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5 và
const items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) => a.localeCompare(b));

// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
1 hoặc liên tục trả lại
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5. Ví dụ: nếu một bộ so sánh chỉ trả về
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
9 và
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5, hoặc chỉ trả về
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5 và
const items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) => a.localeCompare(b));

// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
1, thì nó sẽ không thể sắp xếp một cách đáng tin cậy vì chống đối xứng. Một bộ so sánh luôn trả về
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5 sẽ khiến mảng không được thay đổi, nhưng dù sao cũng đáng tin cậy.

Bộ so sánh từ vựng mặc định thỏa mãn tất cả các ràng buộc ở trên.

Để so sánh các số thay vì các chuỗi, hàm so sánh có thể trừ

function compareNumbers(a, b) {
  return a - b;
}
0 từ
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9. Hàm sau sẽ sắp xếp mảng theo thứ tự tăng dần (nếu nó không chứa
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
0 và
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
1):

function compareNumbers(a, b) {
  return a - b;
}

Phương pháp

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 là chung chung. Nó chỉ mong đợi giá trị
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
3 sẽ có thuộc tính
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
4 và các thuộc tính được khóa. Mặc dù các chuỗi cũng giống như mảng, phương pháp này không phù hợp để được áp dụng trên chúng, vì các chuỗi là bất biến.

Ví dụ

Tạo, hiển thị và sắp xếp một mảng

Ví dụ sau đây tạo ra bốn mảng và hiển thị mảng gốc, sau đó các mảng được sắp xếp. Các mảng số được sắp xếp mà không có hàm so sánh, sau đó được sắp xếp bằng một.

const stringArray = ['Blue', 'Humpback', 'Beluga'];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ['80', '9', '700'];
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']

Sắp xếp mảng các đối tượng

Mảng các đối tượng có thể được sắp xếp bằng cách so sánh giá trị của một trong các thuộc tính của chúng.

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

// sort by value
items.sort((a, b) => a.value - b.value);

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

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

Sắp xếp các ký tự không phải là ASCII

Để sắp xếp các chuỗi với các ký tự không phải ASCII, tức là các chuỗi có các ký tự có dấu (E, é, è, A, ä, v.v.), các chuỗi từ các ngôn ngữ khác ngoài tiếng Anh, sử dụng

// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
5. Hàm này có thể so sánh các ký tự đó để chúng xuất hiện theo đúng thứ tự.

const items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) => a.localeCompare(b));

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

Sắp xếp với bản đồ

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 có thể được gọi nhiều lần cho mỗi phần tử trong mảng. Tùy thuộc vào bản chất của ____ 18, điều này có thể mang lại chi phí cao. Càng nhiều công việc mà
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 thực hiện và càng có nhiều yếu tố để sắp xếp, có thể sử dụng
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
9 hiệu quả hơn để sắp xếp. Ý tưởng là đi qua mảng một lần để trích xuất các giá trị thực tế được sử dụng để sắp xếp thành một mảng tạm thời, sắp xếp mảng tạm thời và sau đó đi qua mảng tạm thời để đạt được thứ tự đúng.

// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);

Có một thư viện nguồn mở có sẵn gọi là Mapsort áp dụng phương pháp này.

Sắp xếp () trả về tham chiếu đến cùng một mảng

Phương thức

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 trả về một tham chiếu đến mảng gốc, do đó, việc biến đổi mảng được trả về cũng sẽ biến đổi mảng gốc.

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10

Trong trường hợp bạn muốn

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 không thay đổi mảng gốc, nhưng trả lại một mảng được sao chép nông như các phương thức mảng khác (ví dụ:
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
9), bạn có thể thực hiện một bản sao nông trước khi gọi
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7, sử dụng cú pháp lan truyền hoặc
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
4.

const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3

Sắp xếp sự ổn định

Kể từ phiên bản 10 (hoặc ECMAScript 2019), đặc điểm kỹ thuật chỉ ra rằng

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
5 ổn định.

Ví dụ, giả sử bạn có một danh sách các học sinh cùng với các lớp của họ. Lưu ý rằng danh sách học sinh đã được sắp xếp trước bằng tên theo thứ tự bảng chữ cái:

const students = [
  { name: "Alex",   grade: 15 },
  { name: "Devlin", grade: 15 },
  { name: "Eagle",  grade: 13 },
  { name: "Sam",    grade: 14 }
];

Sau khi sắp xếp mảng này theo

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
6 theo thứ tự tăng dần:

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
0

Biến

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
7 sau đó sẽ có giá trị sau:

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
1

Điều quan trọng cần lưu ý là các sinh viên có cùng lớp (ví dụ: Alex và Devlin), sẽ vẫn theo cùng thứ tự như trước khi gọi loại. Đây là những gì một thuật toán sắp xếp ổn định đảm bảo.

Trước phiên bản 10 (hoặc Ecmascript 2019), sự ổn định sắp xếp không được đảm bảo, có nghĩa là bạn có thể kết thúc với các điều sau:

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
2

Sắp xếp với bộ so sánh không được hình thành

Nếu một chức năng so sánh không thỏa mãn tất cả các quy tắc tinh khiết, ổn định, phản xạ, chống đối xứng và chuyển tiếp, như được giải thích trong mô tả, hành vi của chương trình không được xác định rõ.

Ví dụ, hãy xem xét mã này:

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
3

Hàm

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 ở đây không được hình thành tốt, bởi vì nó không thỏa mãn tính đối xứng: nếu
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
9, nó sẽ trả về
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
9; Nhưng bằng cách hoán đổi
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
9 và
function compareNumbers(a, b) {
  return a - b;
}
0, nó trả về
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5 thay vì giá trị âm. Do đó, mảng kết quả sẽ khác nhau trên các động cơ. Ví dụ: V8 (được sử dụng bởi Chrome, Node.js, v.v.) và JavaScriptcore (được Safari sử dụng) sẽ không sắp xếp mảng và trả lại
const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
4, trong khi Spidermonkey (được sử dụng bởi Firefox) sẽ trả về mảng được sắp xếp tăng dần, vì
const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
5 .

Tuy nhiên, nếu hàm

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
8 được thay đổi một chút để nó trả về
const items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) => a.localeCompare(b));

// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
1 hoặc
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

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

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
4

Sau đó, V8 và JavaScriptCore sắp xếp nó xuống, như

const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
9, trong khi Spidermonkey trả lại nó như:
const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
4.

Do sự không nhất quán thực hiện này, bạn luôn được khuyên nên làm cho bộ so sánh của bạn được định dạng tốt bằng cách tuân theo năm ràng buộc.

Sử dụng sort () trên các mảng thưa thớt

Các khe trống được di chuyển đến cuối mảng.

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
5

Gọi Sắp xếp () trên các đối tượng không phải là

Phương pháp

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
7 đọc thuộc tính
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
4 của
// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
3. Sau đó, nó thu thập tất cả các thuộc tính khóa nguyên hiện có trong phạm vi
const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort((a, b) => a.value - b.value);

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

  // names must be equal
  return 0;
});
5 đến
const students = [
  { name: "Alex",   grade: 15 },
  { name: "Devlin", grade: 15 },
  { name: "Eagle",  grade: 13 },
  { name: "Sam",    grade: 14 }
];
5, sắp xếp chúng và viết lại chúng. Nếu có các thuộc tính bị thiếu trong phạm vi, các thuộc tính theo dõi tương ứng sẽ bị xóa, như thể các thuộc tính không tồn tại được sắp xếp vào cuối.

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
6

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # sec-array.prototype.sort
# sec-array.prototype.sort

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm