0
  1. I have a json

    var Model = { listAll: function() { var boxes = [{ you:'128'; him:'250'; me:'56' }, { you:'72'; him:'8'; me:'101' }, { you:'224'; him:'97'; me:'35' }, { you:'81'; him:'35'; me:'688' }]; return boxes;
    } };

  2. and I want to SORT it according to property "him" ascendingly.

  3. then I want to throw it in a "for" loop to list all the data of the json ascendingly accordingly to "him" on webpage. The code goes like this:

    <% for(var i=0; i <%= boxes.him %> <%= boxes.you %> <%= boxes.me %>
    <% } %>

Can anyone teach me how to do it?

  • 1
    Show us what you tried, can you post your code so far and a demo to reproduce your particular issue? – elclanrs Feb 21 '14 at 08:52
  • possible duplicate of [Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript) – Felix Kling Feb 21 '14 at 09:07
  • Please note that the data you have is **not** JSON, it's a normal JavaScript object. Your question has **nothing** to do with JSON. – Felix Kling Feb 21 '14 at 09:07
  • possible duplicate of http://stackoverflow.com/questions/8175093/simple-function-to-sort-a-json-object-using-javascript/8175221#8175221 – mr rogers Feb 21 '14 at 09:10

2 Answers2

1

You have errors in that JSON, values shouldn't be terminated with ";" but ",". Here is working example that extends your model and returns sorted list:

var Model = {
  listAll: function() {
    var boxes = [{
      you:'128',
      him:'250',
      me:'56'
    }, {
      you:'72',
      him:'8',
      me:'101'
    }, {
      you:'224',
      him:'97',
      me:'35'
    }, {
      you:'81',
      him:'35',
      me:'688'
    }];
    return boxes;
  },
  listSorted: function() {
    var sortedBoxes = this.listAll();
    return sortedBoxes.sort(function(a,b) {
        return a['him'] - b['him'];
    });
  }
};
console.log(Model.listSorted());
Goran.it
  • 5,991
  • 2
  • 23
  • 25
0

You can do it like this, and you have an example of "for" loop.

var Model = {
    listAll: function () {
        var boxes = [{
            you: '128',
            him: '250',
            me: '56'
        }, {
            you: '72',
            him: '8',
            me: '101'
        }, {
            you: '224',
            him: '97',
            me: '35'
        }, {
            you: '81',
            him: '35',
            me: '688'
        }];

        return boxes;
    }
};

var sortByHim = function (a, b) {
  return a.him - b.him;
}

var sortedList = Model.listAll().sort(sortByHim);

for (var i = 0; i < sortedList.length; i++){
  console.log(sortedList[i].him);
}
Aleksandar Gajic
  • 1,349
  • 1
  • 18
  • 23