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

Time:04-22

Let me exemplify.

Input:

I have a 2 dimension array:

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

And I want to sort them based on the first column => arr[i][0].

But when I sort them using the simple comparison function (a - b), it returns something like:

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

But the expected result must be:

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

Like it was an object.

Reference: Expected result as reference

CodePudding user response:

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);

CodePudding user response:

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));

CodePudding user response:

A version that should allow somewhat arbitrary lengths of version numbers:

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);

  • Related