Prash
Prash

Reputation: 150

Using a function to sort JavaScript objects by values

So if i have an array of objects such as:

var a = [
  {
    name: "Apple",
    rank: 25
  },
  {
    name: "Cherry",
    rank: 29
  },
  {
    name: "Grape",
    rank: 15
  }
]

Is there a way to sort the values say by rank, by calling a function, i have had an attempt at it but keep getting undefined:

function sorting(obj){
    obj.sort(function(a, b){
        return a[1] - b[1];
    })
}

I am struggling to find out where i am going wrong, and am unable to find any documents on MDN regarding this.

Any help would be much appreciated, thanks in advance

Upvotes: 1

Views: 74

Answers (2)

Ashish Patel
Ashish Patel

Reputation: 367

One way you can solve this problem is using Quick Sort algorithm. Below I've implemented the algorithm which will print to the console your array before sort, and array after sort.

 var a = [
    {
    name: "Apple",
    rank: 25
},
    {
    name: "Cherry",
    rank: 29
},
    {
    name: "Grape",
    rank: 15
}
];

console.log(a);

function swap(firstIndex, secondIndex){
    var temp = a[firstIndex];
    a[firstIndex] = a[secondIndex];
    a[secondIndex] = temp;
}

function partition(left, right) {

    var pivot   = a[Math.floor((right + left) / 2)].rank,
        i       = left,
        j       = right;


    while (i <= j) {

        while (parseInt(a[i].rank) < pivot) {
            i++;
        }

        while (parseInt(a[j].rank) > pivot) {
            j--;
        }

        if (i <= j) {
            swap(i, j);
            i++;
            j--;
        }
    }

    return i;
}

function quickSort(left, right) {

    var index;

    if (a.length > 1) {

        left = typeof left != "number" ? 0 : left;
        right = typeof right != "number" ? a.length - 1 : right;

        index = partition(left, right);

        if (left < index - 1) {
            quickSort(left, index - 1);
        }

        if (index < right) {
            quickSort(index, right);
        }
    }
}


quickSort(a);
console.log(a);

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

Both a and b that get passed to sort's callback are the objects from the array. If you want to access their rank property you need to do a.rank not a[1]. Both a[1] and b[1] are undefined because the objects don't have a property called "1":

return a.rank - b.rank;

Example:

var arr = [{ name: "Apple", rank: 25 }, { name: "Cherry", rank: 29 }, { name: "Grape", rank: 15 }];

arr.sort(function(a, b) {
    return a.rank - b.rank;
});

console.log(arr);

Note: To reverse the order of the sorting, do this instead:

return b.rank - a.rank;

Upvotes: 8

Related Questions