Is it possible to get the index you're sorting over in Underscore.js?
Index is actually available like;
_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){ });
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
});
If you'd rather transform your array, then the iterator
parameter of underscore's map
function is also passed the index as a second argument. So:
_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });
... returns:
["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]