rUI7999 rUI7999 - 7 months ago 67
AngularJS Question

Sorting an object by its value using lodash

I’m trying to sort an object alphabetically by its value using loadash only. My sample object is

var object = {AB:'apple',AC:'cat', AD:'bannana', BA:'atom'};

And i’m trying to get output as follows:

Object = {AB: "apple", BA: "atom", AD: "bannana", AC: "cat"}

I tried using _.sortBy, but it doesn’t seems to be working.


There is no such thing as sorting the properties of an object. An object is just an unordered set of key <-> property pairs.

You can create an array with the values of the object and sort them.

As explained in the lodash sortBy documentation, the sortBy method create a sorted array (ie. an ordered list) from the values of a collection. I am not sure that it fits your need. See the following snippet, that use your object as input value.

var object =  {AB:'apple',AC:'cat', AD:'bannana', BA:'atom'};
var sortedValues = _.sortBy(object, function(value) { return value; });
<script src=""></script>

Edit: From your comment, you need to get the (key, value) pairs to iterate over a list of pairs. Here is a proposed solution with a sorted array that is used in a ng-repeat directive.

angular.module('app', [])
  .controller('appCtrl', function($scope) {

    var object = {
      AB: 'apple',
      AC: 'cat',
      AD: 'bannana',
      BA: 'atom'

    var pairs =, function(value, key) {
      return [key, value];

    $scope.sortedPairs = _.sortBy(pairs, function(pair) {
      return pair[1]; // ie. value
<script src=""></script>
<script src=""></script>

<div ng-app="app">
  <ul ng-controller="appCtrl">
    <li ng-repeat="pair in sortedPairs">
      key: {{pair[0]}}, value: {{pair[1]}}