Use Underscore.js to retrieve top n elements from array ranked by some property
javascript, underscore.js
Solution
You can do it with normal javascript, put this in a function and it should work. Just pass in the array you want to sort as `myArray`. Sorry for lack of explanation, on my phone.
var sorted = myArray.sort(function (a, b) {
return a.weight - b.weight; // sort by weight, low to heigh
}).reverse(); // then reverse to get high to low
return sorted.slice(0, 500); // slice the first 500
Problem
I have an array of objects in javascript. Each object is of the form ``` obj { location: "left", // some string weight: 1.25 // some real, positive number } ``` Let us assume the length of the array is greater than 500. I want to return a filtered copy of the array where only the top 500 elements as ranked by the `weight` property are present. In other words, I want the array with objects with the 500 highest `weight`s What is the clean way to do this with underscore?