JSFiddle - React, Tailwind, and code Playground
HTML
<p id="method1"></p>
<p> </p>
<p id="method2"></p>
JavaScript
method1_CombineSortSeparate();
method2_ReorganizeData();
function method1_CombineSortSeparate() {
var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];
//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++)
list.push({'name': names[j], 'age': ages[j]});
//2) sort:
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
//Sort could be modified to, for example, sort on the age if the name is the same.
});
//3) separate them back out:
for (var k = 0; k < list.length; k++) {
names[k] = list[k].name;
ages[k] = list[k].age;
}
var html = "<h3>Method 1: Combine, Sort, and Separate</h3>";
for (var h = 0; h < names.length; h++)
html += names[h] + ", " + ages[h] + "<br />";
document.getElementById("method1").innerHTML = html;
}
function method2_ReorganizeData() {
var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30}
];
list.sort(function(a, b) {
return a.name > b.name;
});
var html = "<h3>Method 2: Reorganize the Data</h3>";
for (var i = 0; i<list.length; i++) {
html += list[i].name + ", " + list[i].age + "<br />";
}
document.getElementById("method2").innerHTML = html;
}