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?
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
each _.each(list, iteratee, [context]) Alias: forEach source. Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.
lodash and Underscore can be categorized as "Javascript Utilities & Libraries" tools. lodash and Underscore are both open source tools. lodash with 39.7K GitHub stars and 4.12K forks on GitHub appears to be more popular than Underscore with 24.6K GitHub stars and 5.41K GitHub forks.
Normally underscore is used in JavaScript to define any field private or public without using private and public keywords. By using underscore (_) we can easily identify the private class and member of that class, so it is a widely used concept in programming language and all programmers will identify it.
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
You can use sortBy()
to sort the array in descending order by weight and use first()
to take the first 500...
var top500 = _.chain(myObjects)
.sortBy(function(item) { return item.weight * -1; })
.first(500)
.value();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With