gpt4 book ai didi

Javascript 数组分组类别

转载 作者:行者123 更新时间:2023-11-30 17:16:23 25 4
gpt4 key购买 nike

我在对数值数组进行分组时遇到问题:

我在这样的数组中有值

var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];

然后按升序排列

var sortedNumb = [1,1,2,3,4,4,5,5,6,6,7,7,8,10,11,12,15,15,18,20];

现在我想创建一组数字

1-4 , 5-8 , 9-12 , 13-16 , 17-20

是否可以像那样动态创建组?

最佳答案

// important code

var numberToGroupOn = 4;

var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
var srt = numb.slice(0).sort(function(a, b) { return a - b; });

var groupCount = Math.ceil(srt[srt.length-1] / numberToGroupOn);

var grps = {};

for(var i = 1; i <= groupCount; i++)
{
grps[((i*numberToGroupOn)-(numberToGroupOn-1)).toString() + '-' + (i*numberToGroupOn).toString()] =
srt.filter(function(a) {return (a <= i*numberToGroupOn) && (a >= (i*numberToGroupOn)-(numberToGroupOn-1))});
}

// unimportant code to see output in SO snippet

var output = '';

for(var key in grps)
{
output += key + ': ' + grps[key]+'<br>';
}

document.write(output);

这会计算出组的数量,然后使用 Array.prototype.filter 构建组的字典.

它只适用于正数。

关于Javascript 数组分组类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054209/

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