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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With