gpt4 book ai didi

javascript - 从下到上对数组进行排序并反向排序。仅获取总数组的 10%

转载 作者:行者123 更新时间:2023-12-01 01:31:20 24 4
gpt4 key购买 nike

"missed_votes_pct" = [4.61, 0.53, 0.18, 0.89, 0.53, 2.3, 4.96, 
0.71, 0.35, 4.26, 0.35, 1.06, 0.89, 1.06,
0.18, 0.89, 9.54, 0, 3.9, 4.26, 0.35, 1.77,
0.35, 0.53, 5.67, 0.35, 1.42, 13.65, 2.66,
0.18, 0.18, 6.38, 0.71, 8.51, 4, 0.35, 0.35,
5.14, 0, 0.35, 0.53, 0.35, 4.61, 3.01, 4.43,
2.13, 1.24, 1.7, 2.13, 10.99, 0.53, 2.09,
0.53, 0.35, 0, 0.53, 0, 0.35, 3.01, 1.77,
0.89, 0.53, 45.56, 2.48, 0, 14.89, 1.77,
4.43, 3.19, 0.35, 2.84, 6.21, 3.55, 1.24,
0.89, 0.71, 0, 0.89, 1.24, 1.6, 6.21, 2.48,
1.06, 2.13, 0.18, 0.89, 65, 3.19, 0.89, 0,
0.89, 3.4, 3.55, 1.06, 0, 3.37, 4.96, 1.06, 0.71,
1.42]

function getTenPerOfMissed(array) {
var temp = [];
var len = array.length * 0.1;
for (var i = 0; i < array.length; i++) {
// console.log(array[i].missed_votes_pct);

if (i < len) {
temp.push(array[i]);
} else if (array[i].missed_votes_pct == array[i - 1].missed_votes_pct) { //find the 10% of the lowest values and keep also values that repeated
temp.push(array[i]);
} else {
break;
}
}
console.log(temp);
}


function bottomTenPercent() {
members.sort(function(a, b) {
return a.missed_votes_pct - b.missed_votes_pct; //sort our array from lower to higher and call getTenPerOfMissed(members)
//to keep the 10% of the lowest values
});
// console.log("Lowest" , members)
getTenPerOfMissed(members)
}


function TopTenPercent() {
members.sort(function(a, b) {
return b.missed_votes_pct - a.missed_votes_pct;
});

getTenPerOfMissed(members);
}


bottomTenPercent();
TopTenPercent();

我创建了这三个函数来对数组进行从高到低的排序和反向排序。另外,我只需要保留 10% 的数字,并且必须保留它们重复的数字。 当我打印带有排序数字的临时数组时,这两个排序函数无法一起工作。如果我只称其中之一工作完美。 另外,我需要访问 temp[],因为我想打印表中的数字。我必须遵循什么过程,因为我根本无法意识到整个过程,并且当我尝试将 temp[] 设置为全局变量时,我的函数无法正常工作有什么想法我做错了吗?因为我已经坚持这个任务两天了。我是 javascript 新手,所以如果我的问题很愚蠢,请原谅我

最佳答案

打开该临时数组的最简单方法是从 getTenPerOfMissed 函数返回它。然后,无论调用什么函数都可以访问修改后的数组。

function getTenPerOfMissed(array) {
var temp = [];
var len = array.length * 0.1;
for (var i = 0; i < array.length; i++) {
// console.log(array[i].missed_votes_pct);

if (i < len) {
temp.push(array[i]);
} else if (array[i].missed_votes_pct == array[i - 1].missed_votes_pct) { //find the 10% of the lowest values and keep also values that repeated
temp.push(array[i]);
} else {
break;
}
}
return temp;
}

var topten = getTenPerOfMissed(array);
// topten is the "temp" array from getTenPerOfMissed

// sort array differently
array.sort(...);
var bottomten = getTenPerOfMissed(array);

关于javascript - 从下到上对数组进行排序并反向排序。仅获取总数组的 10%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53249480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com