qts qts - 11 months ago 63
Node.js Question

Nodejs: sorting paragraph numbers

I am trying to sort some paragraph numbers which have been extracted from a document.

Unfortunately they are not true decimals so the stardard

functions don't work. For example I want the following result: ["3.1","3.2","3.11"] NOT ["3.1","3.11","3.2"] (which is what I get from from using: http://www.w3schools.com/jsref/jsref_sort.asp).

The numbers also have an indeterminate number of decimals. For example they can appear as follows: ["1.i.a","1.i.b","1.i.c.A","1.i.c.B"]

After working on this problem for a while, I believe the best solution is to treat each number as sub-strings separated by '.'s and compare / order them according to the 'lowest' substring.

Can anyone suggest how this can be done in js?

Any help is much appreciated

Answer Source

Does that work for you? I can give more explanation if needed.

"use strict"
let index = ['3.1.a', '3.2', '3.11', '3.1.c', '3.2.z'];

index.sort((a, b) => {
  var aArr = a.split('.'), bArr = b.split('.')

  for (var i = 0, aLength = aArr.length; i < aLength; i++) {
    let aVal = aArr[i], bVal = bArr[i]

    if (bVal === undefined) return 1 // b lower index
    if (aVal === bVal) continue

    return typeof(aVal) === "string" ? aVal.charCode() - bVal.charCodeAt() : aVal - bVal; // for strings, works only if length == 1

  return bArr[i] === undefined ? 0 : -1 // if b undefined, then both numbers are equal, otherwise a is shorter

// outputs [ '3.1.a', '3.1.c', '3.2', '3.2.z', '3.11' ]