Javascript related sort index array

Sorry if this has already been asked, but I did a search for "related javascript sort index array" and didn't find anything satisfying.

I have an array of names and another index-related array that records the frequency with which names appear in a pass, and I want to sort both arrays not alphabetically, but by name frequencies, say the least frequently. I have the following bit of code that does the job adequately, but I think it looks like a hack. There is, of course, a more decent way to solve what should be a fairly common sorting problem.

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

var names = ["Andrew", "Anne", "Archie", "John", "Kristen", "Peter", "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]);
}

      

Now I can list both arrays according to 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.

+1


source to share


2 answers


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);
}

      

0


source


Basically you can use indices and sort them by getting the frequency for a given index.



var names = ['Andrew', 'Anne', 'Archie', 'John', 'Kristen', 'Peter', 'Tom'],
    frequency = [12, 2, 1, 6, 3, 14, 9],
    indices = names.map(function(_, i) { return i; });

indices.sort(function(a, b) {
    return frequency[b] - frequency[a];
});

document.write('<pre>' + JSON.stringify(indices, 0, 4) + '</pre>');
document.write(indices.map(function(a) { return names[a]; }).join('<br>'));
      

Run codeHide result


0


source







All Articles