Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the index you're sorting over in Underscore.js?

I'm using the JS library Underscore and in particular using the _.each and _.sortby library calls. I'm wondering if there's any possible way to get the index of the value within the iterator delegate

_.sortBy([1, 4, 2, 66, 444, 9], function(num){      /*It'd be great to have access to the index in here */     return Math.sin(num);  }); 
like image 763
contactmatt Avatar asked Aug 29 '12 14:08

contactmatt


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What does underscore mean in JavaScript?

Underscore. js provides different types of functions and that function is helpful to programmers to build any type of application without the help of built-in objects. Basically, Underscore is the identifier in JavaScript that means we can identify or we can perform any kind of operation with the help of Underscore.

How do I run an underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


2 Answers

Index is actually available like;

_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){  }); 
like image 78
osoner Avatar answered Sep 26 '22 03:09

osoner


You can get the index of the current iteration by adding another parameter to your iterator function, e.g.

_.each(['foo', 'bar', 'baz'], function (val, i) {     console.log(i + ": " + val); // 0: foo, 1: bar, 2: baz }); 
like image 28
jabclab Avatar answered Sep 26 '22 03:09

jabclab