Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.03k stars 235 forks source link

版本号排序(2023美团暑期实习一面) #494

Open mengqiuleo opened 1 year ago

mengqiuleo commented 1 year ago

有一组版本号如下['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5']。现在需要对其进行排序,排序的结果为 ['4.3.5','4.3.4.5','2.3.3','0.302.1','0.1.1']

mengqiuleo commented 1 year ago
arr.sort((a, b) => {
  let i = 0;
  const arr1 = a.split(".");
  const arr2 = b.split(".");

  while (true) {
    const s1 = arr1[i];
    const s2 = arr2[i];
    i++;
    if (s1 === undefined || s2 === undefined) {
      return arr2.length - arr1.length;
    }

    if (s1 === s2) continue;

    return s2 - s1;
  }
});
console.log(arr);
whale2002 commented 1 year ago
const versions = ["0.1.1", "2.3.3", "0.302.1", "4.2", "4.3.5", "4.3.4.5"];

versions.sort((a, b) => {
  const arr1 = a.split(".").map(Number);
  const arr2 = b.split(".").map(Number);

  const length = arr1.length > arr2.length ? arr1.length : arr2.length;

  for (let i = 0; i < length; i++) {
    const item1 = arr1[i] || 0;
    const item2 = arr2[i] || 0;

    if (item1 === item2) continue;
    return item2 - item1;
  }
});

console.log(versions);