There is an array of the following form:

var myArray = [ '<div id="text13264" onclick="someFunction();"><button>2</button><span>Some text</span></div>', '<div id="text56847" onclick="someFunction();"><button>1</button><span>Some text</span></div>', '<div id="text45487" onclick="someFunction();"><button>3</button><span>Some text</span></div>' ]; 

You need a comparator to sort the array for example (or another):

 myArray.sort(function (a, b) { return a.match(???) - b.match(???); }); 

to sort the elements of the array by the numbers that are inside the tags of the button (in ascending order) and the result is

 <div id="text56847" onclick="someFunction();"><button>1</button><span>Some text</span></div> <div id="text13264" onclick="someFunction();"><button>2</button><span>Some text</span></div> <div id="text45487" onclick="someFunction();"><button>3</button><span>Some text</span></div> 

Those. div with boot 1, then div with boot 2, then div with boot 3, etc. It should be noted that the ID of each div is unique. Although onclick="someFunction();" same for all items

  • And what's wrong with the question? - stckvrw

1 answer 1

 [ '<div id="text13264" onclick="someFunction();"><button>2</button><span>Some text</span></div>', '<div id="text56847" onclick="someFunction();"><button>1</button><span>Some text</span></div>', '<div id="text45487" onclick="someFunction();"><button>3</button><span>Some text</span></div>' ].sort(function (a, b) { return a.match(/\d+(?=<\/button>)/) - b.match(/\d+(?=<\/button>)/); }) 
  • A small additional request: does it happen that inside a button is not just a digit, for example a digit with a question mark or with a letter for example 2? or 26B. Buttons with such symbols are placed separately and sorted incorrectly. How to make the sorting work in such cases? - stckvrw
  • one
    @stckvrw, try (?=\D?<\/button>) . - Qwertiy