2

This is probably a silly question, but how can I sort the below given array based on Values of it's Objects (Ascending Order - 1 to 6).

I can't use Object Key as an identifier since it's dynamic and will change based on User's settings. I got it working using the commented solution, but it doesn't work in IE since IE doesn't support "Object.values" yet.

$scope.data = [            
    { Type: 6 },
    { Path: 1 },
    { Text: 2 },
    { Name: 3 },
    { Icon: 5 },
    { Case: 4 }
];

$scope.data.sort(function (a, b) {
// This commented solution works fine in Chrome and FF, but not in IE since IE doesn't support "Object.values" yet.
//if (Object.values(a) < Object.values(b))
//    return -1;
//if (Object.values(a) > Object.values(b))
//    return 1;
//return 0;

if (a < b)
   return -1;
if (a > b)
   return 1;
return 0;
});

// Desired Result
$scope.data = [
    { Path: 1 },
    { Text: 2 },
    { Name: 3 },
    { Case: 4 },
    { Icon: 5 },
    { Type: 6 }
];
georgeawg
  • 48,608
  • 13
  • 72
  • 95
jshah
  • 33
  • 4

2 Answers2

1

You could sort by the values of the object.

var data = [{ Type: 6 }, { Path: 1 }, { Text: 2 }, { Name: 3 }, { Icon: 5 }, { Case: 4 }];

data.sort((a, b) => Object.values(a) - Object.values(b));

console.log(data);

In IE11 with the first found key of the object.

var data = [{ Type: 6 }, { Path: 1 }, { Text: 2 }, { Name: 3 }, { Icon: 5 }, { Case: 4 }];

data.sort(function (a, b) {
    return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});

console.log(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for your quick asnwer Nina. Your second solution for IE11 fixed the issue. :) – jshah May 01 '18 at 20:34
  • However, just encountered another error (SCRIPT1028: Expected identifier, string or number) in IE11, when I push those objects into that array: for (column in serverData) { var c; if (serverData[column] !== 0) { c = {[column] : serverData[column]}; $scope.data.push(c); } } Any idea what could be wrong on this line - " c = {[column] : serverData[column]};" ? – jshah May 01 '18 at 20:37
  • ie has no computed properties. – Nina Scholz May 01 '18 at 20:39
  • var c = {}; c[column] = serverData[column]; this did the trick. – jshah May 01 '18 at 20:56
0

You can define a function to give you the object values in all browsers, including IE.

This answer has a better example than I came up with: Alternative version for Object.values()

grahamlyons
  • 687
  • 5
  • 15