【问题标题】:Sorting an array of objects based on a property value (int) [duplicate]根据属性值(int)对对象数组进行排序[重复]
【发布时间】:2017-07-18 21:21:08
【问题描述】:

这个问题涉及我的算法以及它为什么不起作用。更具体地说,我想知道如何改进它来做我想做的事情。这就是它与建议的重复问题不同的原因。

我正在尝试创建一个函数,该函数根据它们都共享的属性值 (int) “indexFound”对对象数组进行排序。您可能会怀疑,我试图将 indexFound 较低的元素放在数组的开头。

function organizeTokens(list) {
    for (i = 0; i < list.length - 1; i++) {
        if (list[i].indexFound < list[i + 1].indexFound) {
          // do nothing
        } else if (list[i].indexFound > list[i + 1].indexFound) {
          var tempVal = list[i];
          list[i] = list[i + 1];
          list[i + 1] = tempVal;
        } else {
        // should not happen unless we are comparing the same token
        }
    }
};

就目前而言,当我向它提供一组对象时,这段代码没有任何区别。这些元素仍然不是它们应该的顺序。我是否以正确的方式处理这个问题?我错过了什么明显的东西吗?

编辑:--------------------------------------------- ----------------------

示例输入:organizeTokens([{value: "if", indexFound: 7}, {value: "a", indexFound: 0}])

预期输出:[{value: "a", indexFound: 0}, {value: "if", indexFound: 7}]

实际输出:[{value: "if", indexFound: 7}, {value: "a", indexFound: 0}]

【问题讨论】:

  • 你试过Array.prototype.sort吗?还是您想自己通过算法解决这个问题?
  • 我没有。我现在将检查文档。我正在寻找最有效,最好是最简单的方法来做到这一点 - 因为它只是我正在构建的 Lexer 巨型机器中的一个小齿轮。
  • 您能否发布一个输入数据示例、预期输出数据和您真正得到的输出数据?
  • 当然。 @zer00ne 为您编辑了帖子,请查看。

标签: javascript arrays sorting


【解决方案1】:

您可以使用Array.prototype.sort() 并定义一个比较函数:

function compareIndexFound(a, b) {
  if (a.indexFound < b.indexFound) { return -1; }
  if (a.indexFound > b.indexFound) { return 1; }
  return 0;
}

list.sort(compareIndexFound);

上述比较函数的更简单/简洁的版本:

function compareIndexFound(a, b) {
  return a.indexFound - b.indexFound;
}

使用 ES6:

list.sort((a, b) => a.indexFound - b.indexFound);

你可以定义自己的sortBy函数:

function sortBy(arr, prop) {
  return arr.sort((a, b) => a[prop] - b[prop]);
}

sortBy(list, 'indexFound');

【讨论】:

  • 在我的上下文中,我该如何称呼它? a 和 b 是否都等于同一个令牌列表?像这样的东西?:list.sort(compareIndexFound(tokenList, tokenList))?
  • 编辑:没关系。我得到了它。谢谢您的帮助。这比我尝试做的要简单得多。
【解决方案2】:

你可以使用 JavaScript 的内置排序:

list.sort(function (l, r) {
    return l.indexFound - r.indexFound;
});

如果您使用 lodash 或 underscore 之类的实用程序,它们具有排序功能 这更简单:

var sorted = _.sortBy(list, 'indexFound');

示例:

var list = [
    { indexFound: 9 },
    { indexFound: 3 },
    { indexFound: 17 },
    { indexFound: 1 }
];

var sorted = _.sortBy(list, 'indexFound');

console.log(sorted);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案3】:

    使用带有自定义回调函数的 JS 排序方法。像这样:

    list.sort(function (a, b) {
        return a.indexFound - b.indexFound;
    });
    

    这将按升序排序(从最低到最高)。

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 2021-07-14
      • 2020-09-22
      • 2012-10-22
      • 1970-01-01
      • 2023-03-15
      • 2018-11-14
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多