Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Underscore.js to retrieve top n elements from array ranked by some property

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 weights

What is the clean way to do this with underscore?

like image 529
user1452494 Avatar asked May 28 '14 16:05

user1452494


People also ask

What is the use of _ in JavaScript?

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.

What is _ each?

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.

Which is better Lodash or Underscore?

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.

Is underscore allowed in JavaScript?

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.


2 Answers

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
like image 163
iLikePrograms Avatar answered Oct 01 '22 14:10

iLikePrograms


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();
like image 25
Anthony Chu Avatar answered Oct 01 '22 14:10

Anthony Chu