array-of-arrays-sort-by-col2.12.13

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

§ Quick Take

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

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

§ 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

§ Sorting by a certain column

For example, let's sort this array by second element (column index = 1):

const sortBySubarray = require("array-of-arrays-sort-by-col");
const input = [[1, 9, 0], [1], [1, 8, 2], [1, 7, 5]];
const result = sortBySubarray(input, 1);
console.log(
`${`\u001b[${33}m${`input`}\u001b[${39}m`} = ${JSON.stringify(
input,
null,
0
)}
`

);
// => input = [[1, 7, 5], [1, 8, 2], [1, 9, 0], [1]],

§ API - Input

sortBySubarray(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.

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 array-group-str-omit-num-char 2.1.48
Groups array of strings by omitting number characters
📦 array-includes-with-glob 2.12.42
like _.includes but with wildcards
📦 array-of-arrays-into-ast 1.9.50
turns an array of arrays of data into a nested tree of plain objects
📦 array-pull-all-with-glob 4.12.72
pullAllWithGlob - like _.pullAll but pulling stronger, with globs
📦 arrayiffy-if-string 3.11.38
Put non-empty strings into arrays, turn empty-ones into empty arrays. Bypass everything else.