What I need to know is a way to get the current index
in the pare 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?
What I need to know is a way to get the current index
in the pare 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?
-
I don't think
pare
function haveindex
parameter – Vigneswaran Marimuthu Commented May 11, 2015 at 12:02 - 2 You need the current index of what? All you get is the result sorted... – Mr. Alien Commented May 11, 2015 at 12:02
-
Can you please edit the question and provide an example of what that index looks like? It'd be clear in the case of e.g.
forEach()
but I can't figure out what index you expect in a sort callback function. – Álvaro González Commented May 11, 2015 at 12:06 -
@Mr.Alien both
a
andb
– Afshin Mehrabani Commented May 11, 2015 at 12:16 - Probably a sort function shouldn't take into account the current position of the elements... – Luan Nico Commented May 11, 2015 at 12:17
2 Answers
Reset to default 10Make 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/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.