【问题标题】:How to keep array index>value after sorting排序后如何保持数组索引>值
【发布时间】:2017-06-18 10:03:43
【问题描述】:

在 javascript 中我有下一个数组:

var a = [0, 2, 1, 3];

这个数组索引>值对在哪里:

0 = 0, 1 = 2, 2 = 1, 3 = 3

在对数组进行排序后保持数组索引号的最简单和最优雅的方法是什么。 sort() index>值对之后应该是这样的:

0 = 0, 2 = 1, 1 = 2, 3 = 3

.. 但我应该能够显示这些排序值。问题是数组不能通过跳转索引位置 0、2、1、3 来列出,而只能作为 0、1、2、3。

我能否以某种方式创建一个新数组,其数组值将是那些新的索引位置,然后对这个新数组进行排序但保留以前的索引>值对。

虽然听起来很简单,但我找不到解决办法。

谢谢

附:我实际上想按数组中包含的短语中单词之间的空格数进行排序。然后我想按空格数排序显示(首先是单词最多的短语)。

var input = ["zero", "here two spaces", "none", "here four spaces yes"];
var resort = [];
for (i = 0; i < input.length; i++) {
  var spaces = (input[i].split(" ").length - 1);
  resort.push(spaces); // new array with number of spaces list
}

【问题讨论】:

    标签: javascript arrays sorting


    【解决方案1】:

    您可以将Sorting with map 与保留原始索引和值的新数组一起使用。

    // the array to be sorted
    var list = [0, 2, 1, 3];
    
    // temporary array holds objects with position and sort-value
    var mapped = list.map(function(el, i) {
        return { index: i, value: el };
    })
    
    // sorting the mapped array containing the reduced values
    mapped.sort(function(a, b) {
        return a.value - b.value;
    });
    
    // container for the resulting order
    var result = mapped.map(function(el){
        return list[el.index];
    });
    
    console.log(result);
    console.log(mapped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }´

    【讨论】:

    • 感谢您的帮助。
    【解决方案2】:

    如果您想按重要的内容进行排序,请将回调传递给sort

    input.sort(function(a,b) {
        // b - a for descending order
        return b.split(" ").length - a.split(" ").length;
    });
    

    【讨论】:

    • 嘿@Niet,这很好用!它也很简单。不幸的是,由于我的新名声,我不能给你投票。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2014-06-20
    • 2021-06-10
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多