SirVeritas
SirVeritas

Reputation: 5

Return a String from a Two-Dimensional Array in Javascript

I have a two-dimensional array:

var beatlesComposers = [
  ['George', 22 ],
  ['John', 71 ],
  ['Paul', 71 ],
  ['Ringo', 2 ]
];

The first element is the name of the composer, and the second represents the number of songs written by that composer.

How do I return the name of the composer with the last largest number of songs written (in this instance 'Paul' with 71)?

Upvotes: 0

Views: 63

Answers (2)

Joe Thomas
Joe Thomas

Reputation: 6417

You could always just do a basic Array sort:

var beatlesComposers = [['George', 22 ],['John', 71 ],['Paul', 71 ],['Ringo', 2 ]];

beatlesComposers.sort(function(artist1,artist2){
  return artist2[1]-artist1[1]
});

beatlesComposers[0]; //This is now ['John', 71]

Now the first element in "beatlesComposers" will be the artist with the largest number of songs written.

Upvotes: 0

IrkenInvader
IrkenInvader

Reputation: 4050

You can use reduce to look at the second element of each array and find the highest. Used >= instead of > in the comparison makes the latest element win in case of ties.

var beatlesComposers = [['George', 22 ],['John', 71 ],['Paul', 71 ],['Ringo', 2 ]];

var mostWritten = beatlesComposers.reduce(function(prev, curr){
  return curr[1] >= prev[1] ? curr : prev;
});

Upvotes: 2

Related Questions