Pete Pete - 21 days ago 5
Javascript Question

Sorting objects in array in Javascript

I have a function

urlScores
which return an array of object in the form

[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]


I am asked to sort this array in regards to its score using bubble sort.

What I have tried doing is creating a bubble sorting function that takes the object returned from
urlScores
and sorts it.

function sort(object)
{
for(var i= 0; i < object.length; i++){
if (object[i].score > object[i+1].score) {
var temp = object[i]
object[i]=object[i+1]
object[i+1]=temp
}
}
}


And the function that should be called for sorting the array looks like:

function rankedScores(web,pattern)
{
return (sort(urlScores(web,pattern)))
}


This doesn't seem to be working, I am faced with
TypeError: object[(i + 1)] is undefined


Any help is appreciated

Answer

I have corrected your sort function.

function sort(a) {
    for (var i = 0; i < a.length - 1; i++) {
        if (a[i].score > a[i + 1].score) {
            var temp = a[i]
            a[i] = a[i + 1]
            a[i + 1] = temp
        }
    }
    return a;
}

Here is an example

var arr= '[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]';

console.log(sort(arr));