最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the current index in sort function - Stack Overflow

programmeradmin4浏览0评论

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?

Share Improve this question edited May 11, 2015 at 12:16 Afshin Mehrabani asked May 11, 2015 at 11:59 Afshin MehrabaniAfshin Mehrabani 35k33 gold badges143 silver badges208 bronze badges 6
  • I don't think pare function have index 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 and b – 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
 |  Show 1 more ment

2 Answers 2

Reset to default 10

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/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.

发布评论

评论列表(0)

  1. 暂无评论