MangoPapa7 - 2 years ago 127
Javascript Question

# Javascript sort index linked array

Sorry if this has already been asked but I did search "javascript sort index linked array" and found nothing satisfactory.

I've got an array of names, and another index linked array which records the frequency at which the names appear in a passage, and I want to sort both arrays not alphabetically but according to the name frequencies - say, most frequent to least frequent. I've got the following bit of code which does the job adequately, but I'm thinking that it looks like a hack. Surely there's a more decorous way to solve what must be a pretty common sorting problem.

I start with an array of names[] say, 6 Johns, 2 Annes, 9 Toms, 12 Andrews, 3 Kristens, 1 Archie, and 14 Peters - already sorted alphabetically and counted into frequencies, and the routine below results in an array of indexes to the names and frequency arrays which allows me to display the names and frequencies in order from highest to lowest.

``````var names = [Andrew, Andrew, ..., Anne, Anne, Archie, ..., Tom, Tom, ...];
var frequency = [12, 2, 1, 6, 3, 14, 9];
var holder = [], secondpart = [], numindex = [];
var i;
for (i = 0; i < frequency.length; i++) {
if (frequency[i] < 10) {
holder[i] = "0" + frequency[i] + "!" + i;    // add leading zeros as required
}
if (frequency[i] > 9) {
holder[i] = frequency[i] + "!" + i;    // no leading zeros required
}
}
holder.sort();
holder.reverse();
for (i = 0; i < holder.length; i++) {
secondpart[i] = holder[i].substring(holder[i].indexOf("!") + 1, holder[i].length);
numindex[i] = parseInt(secondpart[i]);
}
``````

I can now list both arrays according to the name frequencies.

``````var txt = "";
var useindex;
for (i = 0; i < numindex.length; i++) {
useindex = numindex[i];
txt = txt + names[useindex] + " - " + frequency[useindex] + "<br>";
}
``````

Has anyone else had this problem and how did you solve it.

try this:

``````var names = ["Adam", "Peter", "Mahu", "Lala"];
var frequencies = [6,2,9,1];

var tupples=[];
for(let i = 0; i<names.length; i++)
{
tupples[i] = {
frequency : frequencies[i],
name : names[i]
};
}

//ascending
//tupples.sort(function(a,b){return a.frequency-b.frequency;});

//descending
tupples.sort(function(a,b){return b.frequency-a.frequency;});

for(let i=0; i<tupples.length; i++)
{
console.debug(tupples[i].name, tupples[i].frequency);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download