Pete Pete - 1 year ago 64
Javascript Question

Sorting objects in array in Javascript

I have a function

which return an array of object in the form


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
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]

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 Source

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}]';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download