I am trying to sort an array into descending order.
This is my current code:
for(var i = 0; i < scoresArray.length; i){
function swap(a, b) {
var temp = scoresArray[a].score;
scoresArray[a] = scoresArray[b].score;
scoresArray[b] = temp;
}
for(var x = 0; x < scoresArray.length; x++){
if(scoresArray[x].score < scoresArray[++x].score){
console.log(x);
swap(x, ++x);
}
}
}
return scoresArray.content;
This is the input array:
[
{ url: 'www.lboro.ac.uk', score: 6 },
{ url: 'www.xyz.ac.uk', score: 3 },
{ url: 'www', score: 8 } ]
This (should be) the output array:
[{ url: 'www.xyz.ac.uk', score: 3 },
{ url: 'www.lboro.ac.uk', score: 6 },
{ url: 'www', score: 8 } ]
Like @Douglas said, using array.sort(compareFunction) makes this easier:
var scoresArray = [
{ url: 'www.lboro.ac.uk', score: 6 },
{ url: 'www.xyz.ac.uk', score: 3 },
{ url: 'www', score: 8 } ];
scoresArray.sort(function(a,b) {
return a.score - b.score;
});
Note that, since scoresArray[i].score
are numbers, you can use return a.score - b.score
. In a more general case (eg if they were strings), you could use
scoresArray.sort(function(a,b) {
if(a.score > b.score) return 1;
if(a.score < b.score) return -1;
return 0;
});
The swap function isn't working, it replaces the values in scoresArray with just the score numbers. It is also important to know that ++x
changes the value of x
. I think you mean x + 1
instead.
This roughly works:
var scoresArray = [
{ url: 'www.lboro.ac.uk', score: 6 },
{ url: 'www.xyz.ac.uk', score: 3 },
{ url: 'www', score: 8 } ];
function swap(a, b) {
var temp = scoresArray[a];
scoresArray[a] = scoresArray[b];
scoresArray[b] = temp;
}
for(var i = 0; i < scoresArray.length; i++) {
for(var x = 0; x < scoresArray.length - 1; x++) {
if (scoresArray[x].score > scoresArray[x + 1].score) {
swap(x, x + 1);
}
}
}
console.log(scoresArray);
But it would be better to use array.sort:
var scoresArray = [
{ url: 'www.lboro.ac.uk', score: 6 },
{ url: 'www.xyz.ac.uk', score: 3 },
{ url: 'www', score: 8 } ];
scoresArray.sort(function(a, b) {
return b.score - a.score;
});
console.log(scoresArray);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.