2

I have an array:

var arr = [ '4msterdam', 'Par1s', 'N3w York', '2urich'];

How can I sort the array by the number that's contained in each element of the array?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Łukasz K
  • 55
  • 3

1 Answers1

1

A good approach would be using Array#sort and RegExp for array sorting, based on the first matched digit in every element.

var arr = ['4msterdam', 'Par1s', 'N3w York', '2urich'];
    sorted = arr.sort((a,b) => a.match(/\d/)[0] - b.match(/\d/)[0]);
    
    console.log(sorted);
kind user
  • 40,029
  • 7
  • 67
  • 77