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

Javascript: Multidimensional array sort by specified index? - Stack Overflow

programmeradmin2浏览0评论

If I have an array that looks like the following:

var array[0] = [$name, $date, $bTrue]; ... ... ...

How would I sort that array by one of the 1st dimensional array values? Thanx in advance!

If I have an array that looks like the following:

var array[0] = [$name, $date, $bTrue]; ... ... ...

How would I sort that array by one of the 1st dimensional array values? Thanx in advance!

Share Improve this question asked Dec 7, 2010 at 22:01 thepip3rthepip3r 2,9356 gold badges33 silver badges42 bronze badges 2
  • Does this answer your question? How to sort 2 dimensional array by column value? – miken32 Commented Jul 25, 2022 at 23:12
  • 1 Peter answered my question 12 years ago. – thepip3r Commented Aug 2, 2022 at 20:44
Add a ment  | 

1 Answer 1

Reset to default 4

With a simple sort callback

var arr = [[1,5,2],[1,8,2],[1,2,2]];

console.log( arr );

arr.sort( function( a, b )
{
  // Sort by the 2nd value in each array
  if ( a[1] == b[1] ) return 0;
  return a[1] < b[1] ? -1 : 1;
});

console.log( arr );

the Array.sort() method takes a callback into which two elements are passed. It's a basic bubble sort

  • If a is to be sorted ahead of b, return -1 (or any negative value)
  • If b is to be sorted ahead of a, return 1 (or any positive value)
  • If a and b are equal, return 0;
发布评论

评论列表(0)

  1. 暂无评论