bobbi.w bobbi.w - 1 year ago 126
Javascript Question

Limit the Results from json

How is it possible to show only 3 Results? I tried it with the for-Loop but it always says NaN. Im using Lodash. Here is my jsFiddle:

I only want to show 3 results. Like I said, I tried it with the for-Loop, when Im not using like this :

for(var i = 0; i<3; i++){
var sorted = _.sortBy(, 'roads').reverse();

it works in the Console. But if I integrate this for-Loop in the jsFiddle, it just breaks:(. I also search for a limit function in Lodash, but it was hopeless.

Answer Source

Use _.take() to limit the results:

var data = {
  "cars": [{
    "number": 5,
    "car_name": "Mercedes",
    "roads": 55
  }, {
    "number": 6,
    "car_name": "Ford",
    "roads": 41
  }, {
    "number": 9,
    "car_name": "Darcia",
    "roads": 36
  }, {
    "number": 3,
    "car_name": "BMW",
    "roads": 61
  }, {
    "number": 11,
    "car_name": "Nissan",
    "roads": 25

var sorted = _.take(_.reverse(_.sortBy(, 'roads')), 3);


/** you can also use a chain **/

var sortedchained = _(

<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download