在 JSON 循环上疯狂排序数组函数

Sorting array function over JSON loops like crazy

所以我正在尝试处理一个函数,但它像疯了一样循环,我不知道为什么。

基本上,我想遍历 json 文件,检索每个“平均”值并将其排序到一个新数组中,因此当我调用函数 ranking(countries[iso].average) 时,它returns数组中的位置。

它确实有效,但 json 文件更大,当我在循环中 console.log(rank) 时,它 returns 超过 27K 条消息。

ranking = (n) => { 
    var rank = [];
    if (n) {
        for (let iso in countries) {
            var newvar = countries[iso].average;            
            rank.push(newvar);
            rank.sort(function(a, b) {
                return b - a;
            });         
        }
        return rank.indexOf(n) + 1   
    }
};  
{"countries":{"US":{"name":"United States of America","ranking":"","average":13.12,"flag":"https://restcountries.eu/data/usa.svg","altNames":["US","USA"],"reports":1302,"cases":0,"deaths":299692,"recovered":23232,"lat":38,"lng":-97,"deltaCases":2,"deltaDeaths":3,"deltaRecovered":0,"casesPerOneMillion":2,"deathsPerOneMillion":903,"totalTests":22323,"testsPerOneMillion":3434,"population":345},"IN":{"name":"India","ranking":"","average":10.22,"flag":"https://restcountries.eu/data/ind.svg","altNames":["IN","Bhārat"],"reports":1016,"cases":9796992,"deaths":142222,"recovered":9290834,"lat":20,"lng":77,"deltaCases":null,"deltaDeaths":null,"deltaRecovered":646,"casesPerOneMillion":7068,"deathsPerOneMillion":103,"totalTests":151632223,"testsPerOneMillion":109402,"population":1295210000},"RU":{"name":"Russian Federation","ranking":"","average":13.21,"flag":"https://restcountries.eu/data/rus.svg","altNames":["RU","Rossiya"],"reports":1321,"cases":2597711,"deaths":45893,"recovered":2059840,"lat":60,"lng":100,"deltaCases":28585,"deltaDeaths":613,"deltaRecovered":26171,"casesPerOneMillion":17797,"deathsPerOneMillion":314,"totalTests":81564365,"testsPerOneMillion":558804,"population":146599183}}}

感谢您对此的任何帮助

我相信您可能想要做的是按 iso 中称为国家平均值的字段排序。所以你有一些名为 countries 的查找,那里有我想象的 ISO:'US'。那么Rank就是所有这些国家的数组。

我看到的问题是您在 for 循环中发生了排序。

您解释问题的方式似乎分为两个不同的步骤。一个检索平均值,然后按平均值排序。

如果你真的想要数组中的平均值:你可以这样做

const averages = Object.values(countries).map(country => country.average)

这一步将使您将所有平均值放入一个数组中。

接下来您可以使用您发布的相同功能进行排序。 (关键是将其制动到第二个循环而不是嵌套循环:

averages.sort((a, b) => b - a) // 现在排序

但如果您想保留其余数据,您也可以很容易地做到这一点:

更像是:

const countriesSortedByAverage = Object.values(countries).sort((a, b) => b.average - a.average)

如果你真的需要 ISO,你也可以用 Object.entries 做同样的事情,但在国家对象中提供 iso 可能更容易。

要确定所有国家/地区的排名,您可以轻松地将其添加到(如果需要)并将其作为主要国家/地区对象:

const RANKED_LIST_OF_COUNT = countriesSortedByAverage.map((countryObj, rank) => ({ ...countryObj, rank }))

如果想进一步还原为CountriesByISO对象:

const COUNTRIES_BY_ISO_WITH_RANK = Object.assign({}, ...RANKED_LIST_OF_COUNT.map(country => ({ [country.ISO]: country}))
)