Reputation: 27
I currently have an array that has ~2000 arrays within. Within those secondary arrays, there is a "point" output. I would like to sort the initial array by point value (highest to lowest). here's an example of the JSON (this include the array with only three arrays, keep in mind the production array has 2000 items)
[ [ 'Tony Parker',
'Greivis Vasquez',
'Manu Ginobili',
'Tyreke Evans',
23400,
98.25 ],
[ 'Tony Parker',
'Greivis Vasquez',
'Manu Ginobili',
'Eric Gordon',
20500,
86.87 ],
[ 'Tony Parker',
'Greivis Vasquez',
'Manu Ginobili',
'DeMar DeRozan',
23200,
97.97 ],
]
The point value is the equivalent of data[0][5], data[1][5].... data[2000][5]
.
While I know there is a sort function within Javascript, I'm not clear as to how to use the sort function for items based within a secondary array, then to compare to other point values in secondary arrays. Thoughts?
Upvotes: 0
Views: 86
Reputation: 16068
A simple custom sort should do the trick:
var arr = [ [ 'Tony Parker', 'Greivis Vasquez', 'Manu Ginobili', 'Tyreke Evans', 23400, 98.25 ], [ 'Tony Parker', 'Greivis Vasquez', 'Manu Ginobili', 'Eric Gordon', 20500, 86.87 ], [ 'Tony Parker', 'Greivis Vasquez', 'Manu Ginobili', 'DeMar DeRozan', 23200, 97.97 ] ]
arr.sort(function(a,b){ // a and b are the 2 arrays to compare
return b[5] - a[5] // sort by descending, using the point value
})
console.log(arr)
Upvotes: 1