javascript - 根据属性值(int)对对象数组进行排序

标签 javascript arrays sorting

这个问题在这里已经有了答案:





JavaScript: Sort an array of objects by a numeric property in each object [duplicate]

(4 个回答)


5年前关闭。




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

我正在尝试创建一个函数,该函数根据它们共同共享的属性值(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()并定义一个比较函数:

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');

关于javascript - 根据属性值(int)对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499698/

相关文章:

javascript - 如何根据与单词的匹配程度对二维数组进行排序?

tsql - SQL 中的排序

javascript - Alexa node.js 授权 http 请求

javascript - Angular : What is the best way to bind to a global event in a directive

javascript - 将对象推送到数组有时不起作用

php - 有没有更好的方法来转置 PHP 二维数组?

javascript - 按属性过滤掉对象(不删除)

c - 在 C 中实现 FIFO 列表

c - 用 C qsort() 排序结构

c# - 排序列表<xyz <String,String >>,错误: InvalidOperationException的问题