【问题标题】:How to sort an array in lexiographicall order如何按字典顺序对数组进行排序
【发布时间】:2020-09-26 06:35:37
【问题描述】:

我的目标是对以下数组lexiographically 进行排序。 取以下数组:

['abc', 'xyz', 'hij', 'def']

最后应该是这样的:

['abc', 'def', 'hij', 'xyz']

我找到了这个question,它展示了如何在对象数组上实现它,但我不知道如何转换它对“正常”数组进行排序的代码。

【问题讨论】:

  • console.log(['abc', 'xyz', 'hij', 'def'].sort())
  • a = ['abc', 'xyz', 'hij', 'def']; a.sort()

标签: javascript sorting


【解决方案1】:

你可以使用数组sort:

var array = ['abc', 'xyz', 'hij', 'def'];
console.log(array.sort());

【讨论】:

    【解决方案2】:

    As you can see in the ECMAScript Language Specification, lexicographic ordering is the default for strings.

    事实上,这也是数字的默认值,这非常烦人:

    const ns = [4, 18, 8, 6, 1, 15, 7, 16, 17, 9, 13, 2, 3, 11, 12, 14, 20, 19, 10, 5];
    
    console.log(ns.sort());
    // [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 3, 4, 5, 6, 7, 8, 9]

    因此,您可以简单地将Array.prototype.sort 与默认比较器一起使用,如下所示:

    const strings = ['abc', 'xyz', 'hij', 'def'];
    
    console.log(strings.sort());
    // ['abc', 'def', 'hij', 'xyz']

    您可以看到in the specification for Array.prototype.sort,它委托给Abstract Relation Comparison Operation,在步骤#3 中执行字典比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2014-04-11
      相关资源
      最近更新 更多