array-of-arrays-sort-by-col3.0.16

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

§ Quick Take

import { strict as assert } from "assert";
import { sortByCol } from "array-of-arrays-sort-by-col";

// sort by second column, index number 1
assert.deepEqual(
  sortByCol([[1, 9, 4], [1], [1, 9, 3], [1, 9, 2]], 1),
  [[1, 9, 2], [1, 9, 3], [1, 9, 4], [1]]
);

§ Examples

§ Purpose

Sorts array of arrays by any column (default is 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 we compare two rows, first we compare by particular column (default is first, zero-index column). Then, if values are equal, we look around and compare 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. ...
  • We accept arrays, normalised into a matrix, with absent value fillings set to null. Same behaviour.

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

§ API - Input

sortByCol(arr, [index])

In other words, it's a function which takes two input arguments:

Input argumentTypeObligatory?Description
arrArray of zero or more arraysyesSource of data to put into an AST
indexNatural number or zero, like a number or stringnoBy which column should we match the subarrays (rows)? The default is 0 or the first element of each sub-array.

§ API - Output

Same array of arrays, only sorted.

§ Changelog

See it in the monorepo opens in a new tab, on GitHub.

§ Contributing

To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.

§ Licence

MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 array-pull-all-with-glob 5.0.16
Like _.pullAll but with globs (wildcards)
📦 arrayiffy-if-string 3.13.16
Put non-empty strings into arrays, turn empty-ones into empty arrays. Bypass everything else
📦 array-of-arrays-into-ast 2.0.16
Turns an array of arrays of data into a nested tree of plain objects
📦 array-includes-with-glob 3.0.16
Like _.includes but with wildcards
📦 array-group-str-omit-num-char 4.0.16
Groups array of strings by omitting number characters