Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→array-of-arrays-sort-by-colnext

array-of-arrays-sort-by-col

Sort array of arrays by column, rippling the sorting outwards from that column

Downloads per monthMIT Licenselibera manifesto
  • the top
  • API — SORTBYCOL()
  • API — VERSION
  • PURPOSE

API — sortByCol()

The main function sortByCol() is imported like this:

It is a function which takes two input arguments:

Input argumentTypeObligatoryDescription
arr
Type: Array of zero or more arrays
Obligatory: yes
arrArray of zero or more arraysyesSource of data to put into an AST
index
Type: Natural number or zero, like a number or string
Obligatory: no
indexNatural number or zero, like a number or stringnoWhich column to match the subarrays (rows) by? The default is 0 or the first element of each sub-array.

The function returns a sorted array.

API — version

You can import version:

Purpose

Sorts array of arrays by any column (the default is the first element, zero’th column index).

The algorithm is tailored for integer-only values.

Consider this arrangement:

1 ----- 9 ----- 0
1 ---------------
1 ----- 8 ----- 2
1 ----- 7 ----- 5

In JS code, that’s:

[[1, 9, 0], [1], [1, 8, 2], [1, 7, 5]];

Default sorting is against first column (zero’th index), so result would be:

1 ----- 7 ----- 5
1 ----- 8 ----- 2
1 ----- 9 ----- 0
1 ---------------

Output in JS code:

[[1, 7, 5], [1, 8, 2], [1, 9, 0], [1]];

Rules:

  • When two rows are compared, the program compares by a particular column first (default is the first, zero-index column). Then, if values are equal, it looks around and compares by those values. First, compare left-side, then right-side. Then, if values are equal even there, we “ripple” outwards. First, compare left-side, then right-side. Then, if values are equal even there, we “ripple” outwards. …
  • Arrays normalised into a matrix, with absent values filled in as null, are accepted too. Same behaviour.
1 ---- 7 ------ 5
1 ---- 8 ------ 2
1 ---- 9 ------ 0
1 --- null -- null
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab