这个问题涉及到我的算法以及为什么它不能正常工作。更具体地说,我想知道如何改进它,使其实现我想要的功能。这就是为什么它不同于建议的重复问题的原因。
我正在尝试创建一个函数,根据它们共同拥有的属性值(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
吗?还是你想自己算法地解决这个问题? - Yeldar Kurmangaliyev