Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current index in sort function

Tags:

javascript

What I need to know is a way to get the current index in the compare function of sort method in an array. Suppose this code:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) { 
  return a - b; 
  //i need the current index of `a` and `b` here 
});

In the anonymous function, I need the current index of a and b objects. How can I get it?

like image 315
Afshin Mehrabani Avatar asked May 11 '15 11:05

Afshin Mehrabani


2 Answers

Make an array of objects with 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 i = 0, j = arr2.length; i < j; i++){
    console.log('i:', i, 'arr2[i].obj:', arr2[i].obj);
}

fiddle: https://jsfiddle.net/k6xdqpb2/

like image 68
deostroll Avatar answered Sep 20 '22 03:09

deostroll


The index of a or b?

var indexOfA = points.indexOf(a);

This will give you the index that a first appears in the array.

Depending on what you are trying to do, another option may be to use a map for sorting as described in more details under the 'Sorting with map' heading here. An example of this approach is given in deostroll's answer.

like image 45
djskinner Avatar answered Sep 21 '22 03:09

djskinner