像Python一样按值对JS数组进行排序

All*_*mon 2 javascript python

注意:该问题在首次回答后已从根本上更新

我如何在 JS 中执行与 python 代码sort(array)或array.sort()(就地)等效的数组排序,如下例所示:

data = [
    { 'id': [2], 'other properties': ... },
    { 'id': [1,3,0,00,15], 'other properties': ... },
    { 'id': [1,0,0], 'other properties': ... },
    { 'id': [1,3,0,00,14], 'other properties': ... },
    { 'id': [1,3,0], 'other properties': ... },
]

data.sort(key = lambda e: e['id'] )


# output 
data == 
    [
        { 'id': [1, 0], 'other properties': ...},
        { 'id': [1, 0, 0], 'other properties': ...},
        { 'id': [1, 3, 0], 'other properties': ...},
        { 'id': [1, 3, 0, 0, 14], 'other properties': ...},
        { 'id': [1, 3, 0, 0, 15], 'other properties': ...},
        { 'id': [2] 'other properties': ...},
    ]
Run Code Online (Sandbox Code Playgroud)

Glu*_*tor 7

所以......我无意中想知道数组的排序方法是如何工作的,它看起来确实与我的直觉相反,但也许只是我。

不管怎样......考虑到我的Python背景,我决定编写一个sorted函数来尝试实现Python的排序逻辑。

该函数返回一个排序数组而不修改原始数组。

有两个可选参数以kwargs对象的形式作为第二个参数传递。

可选参数有:

  • reverse- 当reverse是false(默认)时,排序为升序,如果是true,则排序为降序。
  • key- 是一个key生成器函数,它处理items数组,生成具有原始位置的键,然后使用基元之间的简单比较或类似于 python 的类似比较的元组对键进行排序

对键数组进行排序后,原始数组将根据键在排序输出中的位置排序返回。

来源:

function sorted(items, kwargs={}) {
    const key = kwargs.key === undefined ? x => x : kwargs.key;
    const reverse = kwargs.reverse === undefined ? false : kwargs.reverse;
    const sortKeys = items.map((item, pos) => [key(item), pos]);
    const comparator =
        Array.isArray(sortKeys[0][0])
        ? ((left, right) => {
            for (var n = 0; n < Math.min(left.length, right.length); n++) {
                const vLeft = left[n], vRight = right[n];
                const order = vLeft == vRight ? 0 : (vLeft > vRight ? 1 : -1);
                if (order != 0) return order;
            }
            return left.length - right.length;
        })
        : ((left, right) => {
            const vLeft = left[0], vRight = right[0];
            const order = vLeft == vRight ? 0 : (vLeft > vRight ? 1 : -1);
            return order;
        });
    sortKeys.sort(comparator);
    if (reverse) sortKeys.reverse();
    return sortKeys.map((order) => items[order[1]]);
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

console.log(sorted([-1, 9, -3, 4, -3, 6, 1, -7], {reverse: true}));
console.log(sorted([-1, 9, -3, 4, -3, 6, 1, -7]));
console.log(sorted(["U", "z", "Z", "f", "F", "a", "c", "d", "x"], {key: x => [x.toLowerCase(), x]}));
console.log(sorted(['-1', '9', '-3', '4', '-3', '6', '1', '-7', '11111']));
console.log(sorted(['-1', '9', '-3', '4', '-3', '6', '1', '-7', '11111'], {key: x => parseFloat(x)}));

data = [
    { 'id': [2], 'other properties': null },
    { 'id': [1,3,0,00,-15], 'other properties': null },
    { 'id': [1,-3,0,00,15], 'other properties': null },
    { 'id': [1,-3,0,00,-15], 'other properties': null },
    { 'id': [1,0,0], 'other properties': null },
    { 'id': [1,3,0,00,14], 'other properties': null },
    { 'id': [1,3,0], 'other properties': null },
]

console.log("PY asc", sorted(data, {key: x=>x.id}))

console.log("JS asc", [...data].sort(x=>x.id))

console.log("PY desc", sorted(data, {key: x=>x.id, reverse: true}))

console.log("JS desc", [...data].sort(x=>x.id).reverse())
Run Code Online (Sandbox Code Playgroud)

原始问题提供的数据的输出:

PY asc [
  { id: [ 1, -3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, 15 ], 'other properties': null },
  { id: [ 1, 0, 0 ], 'other properties': null },
  { id: [ 1, 3, 0 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, 14 ], 'other properties': null },
  { id: [ 2 ], 'other properties': null }
]
JS asc [
  { id: [ 2 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, 15 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, 0, 0 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, 14 ], 'other properties': null },
  { id: [ 1, 3, 0 ], 'other properties': null }
]
PY desc [
  { id: [ 2 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, 14 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, 3, 0 ], 'other properties': null },
  { id: [ 1, 0, 0 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, 15 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, -15 ], 'other properties': null }
]
JS desc [
  { id: [ 1, 3, 0 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, 14 ], 'other properties': null },
  { id: [ 1, 0, 0 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, -15 ], 'other properties': null },
  { id: [ 1, -3, 0, 0, 15 ], 'other properties': null },
  { id: [ 1, 3, 0, 0, -15 ], 'other properties': null },
  { id: [ 2 ], 'other properties': null }
]
Run Code Online (Sandbox Code Playgroud)

这就是大家。