Pete Pete - 5 months ago 24
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


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