JavaScript排序索引链接数组 [英] Javascript sort index linked array

查看:52
本文介绍了JavaScript排序索引链接数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,是否已经被询问过,但是我确实搜索了 javascript排序索引链接数组,却发现没有令人满意的结果。

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.

我从一组名称开始[]说,约翰斯6岁,安妮2岁,9岁汤姆斯(Toms),12安德鲁斯(Andrews),3克里斯滕斯(3 Kristens),1阿奇(Archie)和14彼得斯(Peters)-已经按字母顺序排序并计入频率,下面的例程生成名称和频率数组的索引数组,使我可以按顺序显示名称和频率从最高到最低。

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", "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]);
}

我现在可以根据名称频率列出两个数组。

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.

推荐答案

尝试一下:

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

这篇关于JavaScript排序索引链接数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆