-6

I would like to sort the following array by the max value of the index 0, and print the value and the index 1 of the corresponding array in Javascript:

[ 
  [ 600, 'marketing' ],
  [ 1500, 'it' ],
  [ 4200, 'healthy' ] 
  [ 2400, 'fitness' ],
  [ 3300, 'payment' ],
]

Like for example in this case: [ 4200, 'healthy' ]

guiandmag
  • 107
  • 3
  • There are plenty of tutorial on this stuff out there. Try writing some code then asking for help if it's not working. – Difster Jul 08 '17 at 18:43
  • possible duplicate of https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly – Naga Sai A Jul 08 '17 at 18:43
  • Have you tried anything? StackOverflow isn't a free "write code for me" service. Have you looked at [`Array.prototype.sort`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) for example? – glhrmv Jul 08 '17 at 18:44
  • 1
    FWIW, if all you need is the max value, a `.reduce()` is actually more appropriate… – deceze Jul 08 '17 at 18:44

1 Answers1

0

You can use array.sort, using a compare function:

var arr = [ 
[ 600, 'marketing' ],
[ 1500, 'it' ],
[ 4200, 'healthy' ] 
[ 2400, 'fitness' ],
[ 3300, 'payment' ],
];
var compare = function(a,b) {
if (a[0]>b[0]) return 1; 
else if (a[0]<b[0])return -1;
return 0;
}

arr.sort(compare);