根据第一列对二维数组进行排序,其中值为 'version-dotted' 字符串 JS

Sort 2 dimension array based in 1st column where the value is a 'version-dotted' string JS

让我举例说明。

输入:

我有一个二维数组:

arr = [['13.12', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com']]

我想根据第一列对它们进行排序 => arr[i][0]。

但是当我使用简单的比较函数 (a - b) 对它们进行排序时,它 returns 类似于:

output: [['13.12', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com']]

但预期的结果必须是:

expected 'version sorted': [['13.2', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com'], ['13.12', 'www.randomLinkHere.com']]

就像一个物体。

参考:Expected result as reference

const arr = [
  ["13.12", "www.randomLinkHere.com"],
  ["14.1", "www.randomLinkHere.com"],
  ["15.1", "www.randomLinkHere.com"],
  ["15.3", "www.randomLinkHere.com"],
  ["16.2", "www.randomLinkHere.com"],
  ["13.2", "www.randomLinkHere.com"],
  ["13.13", "www.randomLinkHere.com"],
  ["13.113", "www.randomLinkHere.com"],
  ["1.2", "www.randomLinkHere.com"],
  ["2.2", "www.randomLinkHere.com"],
  ["125.2", "www.randomLinkHere.com"],
];

const sortedArr = arr.sort(
  (a, b) =>
    a[0].split(".").reduce((acc, val) => acc * 10000 + parseFloat(val), 0) -
    b[0].split(".").reduce((acc, val) => acc * 10000 + parseFloat(val), 0)
);
console.log(sortedArr);

const arr = [
    ['13.12', 'www.randomLinkHere.com'],
    ['13.6', 'www.randomLinkHere.com'],
    ['13.2', 'www.randomLinkHere.com'],
];

const sortArr = (arr) => {
    return arr.sort((a, b) => {
            if (+a[0] > +b[0]) return 1;
            return 0;
        }).reverse();
};

console.log(sortArr(arr));

一个应该允许任意长度的版本号的版本:

const arr = [
  ["13.12", "www.randomLinkHere.com"],
  ["13.6", "www.randomLinkHere.com"],
  ["13.2", "www.randomLinkHere.com"],
  ["14.1", "www.randomLinkHere.com"],
  ["13.110", "www.randomLinkHere.com"],
  ["13.11.3", "www.randomLinkHere.com"],
  ["13.1090.3", "www.randomLinkHere.com"],
];

const compare_versions = (a, b) => {
  const a_parts = a.split('.');
  const b_parts = b.split('.');
  
  for(let i = 0; i < Math.max(a_parts.length, b_parts.length); i++) {
    let comp = +(a_parts[i] ?? 0) - +(b_parts[i] ?? 0);
    if(comp !== 0) return comp;
  }
  
  return 0;
};

const sortedArr = arr.sort(([a], [b]) => compare_versions(a, b));
console.log(sortedArr);