Group by - Custom function
-
I have following row data in a json file: {rows:[ {id:1,data:["1","A","10"]} ,{id:2,data:["2","B","50"]} ,{id:3,data:["3","C","60"]} ,{id:4,data:["4","D","70"]} ,{id:5,data:["5","E","90"]} ,{id:6,data:["6","F","2"]} ,{id:7,data:["7","G","4"]} ,{id:8,data:["8","H","50"]} ,{id:9,data:["9","B","100"]} ,{id:10,data:["10","A","60"]} ,{id:11,data:["11","K","0"]} ,{id:12,data:["12","L","20"]} ]} I was wondering if I can get a kick start suggestion to write our own group by function to group on any column. Like in above example, we can use the second column to group by. The only restriction I have is that I can't use jquery and have to use java script only. Need expert help...
-
I have following row data in a json file: {rows:[ {id:1,data:["1","A","10"]} ,{id:2,data:["2","B","50"]} ,{id:3,data:["3","C","60"]} ,{id:4,data:["4","D","70"]} ,{id:5,data:["5","E","90"]} ,{id:6,data:["6","F","2"]} ,{id:7,data:["7","G","4"]} ,{id:8,data:["8","H","50"]} ,{id:9,data:["9","B","100"]} ,{id:10,data:["10","A","60"]} ,{id:11,data:["11","K","0"]} ,{id:12,data:["12","L","20"]} ]} I was wondering if I can get a kick start suggestion to write our own group by function to group on any column. Like in above example, we can use the second column to group by. The only restriction I have is that I can't use jquery and have to use java script only. Need expert help...
You can overload the standard Array.sort() in the same manner as a standard comparative operation. The problem that you have is that your rows are not properly formatted for JSON (it looks like your data value should be an object, not an array) and you're mixing strings and integers. If you ONLY want to group by 1 field that's easy, if you want flexibility then you'll have a more complicated operation on your hands. One sort function will not be suitable for your needs, since string comparisons in Javascript will give you wonky results when used on stringified numbers, and using numerical comparisons on strings will also give bad data. Array.prototype.sort() - JavaScript | MDN[^] has a bunch of suggestions for how to handle sorting of various data types and uses vanilla Javascript.