javascript - Get the current index in sort function -
what need know way current index in compare function of sort method in array. suppose code:
var points = [40, 100, 1, 5, 25, 10]; points.sort(function (a, b) { return - b; //i need current index of `a` , `b` here }); in anonymous function, need current index of a , b objects. how can it?
make array of objects indices...
var arr = [1,5,2,3,8,13, 1]; var arr2 = arr.map(function(o, i) {return {idx: i, obj: o}; }).sort(function(a, b) { console.log('a.idx:', a.idx, 'b.idx:', b.idx); return a.obj - b.obj; }); for(var = 0, j = arr2.length; < j; i++){ console.log('i:', i, 'arr2[i].obj:', arr2[i].obj); } fiddle: https://jsfiddle.net/k6xdqpb2/
Comments
Post a Comment