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
  • 51,385
  • 12
  • 117
  • 139
Ł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
  • 34,867
  • 6
  • 60
  • 74