-2

I have an array as follows:

var array = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

I want to sort the array by mark field. How can I achieve this?

UPDATE

I used the following function to sort the above array object by mark.

$scope.GetSortOrder = function(prop) {  
    return function(a, b) {  
        if (a[prop] > b[prop]) {  
            return 1;  
        } else if (a[prop] < b[prop]) {  
            return -1;  
        }  
        return 0;  
    }  
};

array.sort($scope.GetSortOrder("mark"));

But then I get the following error

array.sort is not a function

Desired output

  var outPut = 
  {
    "week1":[
       {"id":1,"name":"x","mark":"20"},
       {"id":2,"name":"y","mark":"30"}
    ],
    "week2":[
       {"id":3,"name":"z","mark":"10"},
       {"id":1,"name":"x","mark":"40"},
       {"id":2,"name":"y","mark":"60"}
    ]
  }
georgeawg
  • 48,608
  • 13
  • 72
  • 95
tharindu
  • 513
  • 6
  • 26

1 Answers1

2

var array is not an array (it's an object), therefore you can't use .sort() on it.

It looks like you want to sort the object's values. If so, you want to fetch the object's values using Object.values(), loop through them, and sort those instead.

var obj = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

Object.values(obj).forEach(arr => arr.sort((a,b) => a.mark-b.mark));

console.log(obj);

If you preferred a method that accepts a property name (like in your example), perhaps this curried approach would work for you.

var obj = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

const sortArrayByProperty = prop => arr => arr.sort((a,b) => a[prop].localeCompare(b[prop]));

Object.values(obj).forEach(sortArrayByProperty("mark"));

console.log(obj);
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56