Str*_*mer 2 javascript arrays sorting
这个问题涉及我的算法以及它为什么不起作用.更具体地说,我想知道如何改进它来做我想做的事情.这就是为什么它与建议的重复问题不同.
我试图创建一个函数,根据它们共同共享的属性值(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
}
}
};
Run Code Online (Sandbox Code Playgroud)
按照目前的情况,当我提供一个对象数组时,这段代码没有任何区别.元素仍然不是它们应该的顺序.我是以正确的方式接近这个吗?我错过了一些明显的东西吗
编辑:------------------------------------------------ -------------------
示例输入: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);
Run Code Online (Sandbox Code Playgroud)
上述比较功能的简单/简洁版本:
function compareIndexFound(a, b) {
return a.indexFound - b.indexFound;
}
Run Code Online (Sandbox Code Playgroud)
使用ES6:
list.sort((a, b) => a.indexFound - b.indexFound);
Run Code Online (Sandbox Code Playgroud)
您可以定义自己的sortBy功能:
function sortBy(arr, prop) {
return arr.sort((a, b) => a[prop] - b[prop]);
}
sortBy(list, 'indexFound');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3929 次 |
| 最近记录: |