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

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your quick asnwer Nina. Your second solution for IE11 fixed the issue. :)
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]};" ?
ie has no computed properties.
var c = {}; c[column] = serverData[column]; this did the trick.
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.