17

This is an example of my JSON file.

[
    {"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
    {"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
    {"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
    {"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
    {"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
    {"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
    {"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
    {"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
    {"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
    {"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO  HALOO","Variable1":0}
]

How can I get only the Top 10 from highest Variable1 number to the least? But gonna be passing the JSON file as the same format.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Gio Perez
  • 207
  • 1
  • 2
  • 12

2 Answers2

22

First, parse the JSON into an array of Objects:

var data = JSON.parse(json);

Then combine sort and slice to achieve your goal:

var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
                .slice(0, 10);

See Array.sort

haim770
  • 48,394
  • 7
  • 105
  • 133
  • There's a typo in the comparison. Should be ``a.Variable1 > b.Variable1`` – LongZheng Nov 24 '16 at 10:27
  • No, having `a.Variable1 > b.Variable1` will show you the generate an array and show lowest values. Old post, but may be helpful for someone who wants to save a minute. – Paulius K. Mar 13 '18 at 04:13
  • @LongZheng [No](https://stackoverflow.com/q/24080785/1048572) – Bergi Mar 04 '23 at 19:59
5

You can do it with Alasql JavaScript library. It download json file, parse it, and run SQL statement on it. This is a sample how to take top 10 directly from JSON file:

<script src="alasql.min.js></script>
<script>
    alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){
        console.log(top10);
    });
</script>

Or if you already have data in memory:

    var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
    var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);

Try this sample in jsFiddle.

agershun
  • 4,077
  • 38
  • 41