How to return customize group by using underscore js?

68 Views Asked by At

I'm calling and binding data using rest api and trying to manage group by functionality using underscore js. But I can't determine how could I do that.

Here is my returned data image: enter image description here

I'm doing group by on int value that works fine but my expected output is group by 0-1,1-2,2-3 by distance value suppose array is returning distance 0,0.224,0.50,1.22 then output should be in two array 0: 0,0.224,0.50 and 1: 1.22

Thanks.

1

There are 1 best solutions below

2
Mikhail Shabrikov On BEST ANSWER

If I understand you correctly you should use

_.groupBy(data.response.data, function(d) { return Math.floor(d.distance); })

in this case you will get the output that you expect. Check the demo:

var array = [0,0.224,0.50,1.22]

console.log(_.groupBy(array, Math.floor));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>