bobbi.w bobbi.w - 1 month ago 18
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: https://jsfiddle.net/kxohm0qh/.

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

for(var i = 0; i<3; i++){
var sorted = _.sortBy(data.car, 'roads').reverse();
console.log(sorted[i]);
}


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

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(data.cars, 'roads')), 3);

console.log(sorted);

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

var sortedchained = _(data.cars)
  .sortBy('roads')
  .reverse()
  .take(3)
  .value();

console.log(sortedchained);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>