JavaScript数组分组类别(Javascript Array grouping categor

2019-10-21 01:40发布

我有分组数值的阵列的问题:

我有值这样的阵列

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

是否有可能创建组动态,喜欢吗?

Answer 1:

假设1-4,5-8,9-12,13-16,17-20分组意味着想要5组,第一个(1-4)含有[1,4]区间内的所有号码; 含有[5,8]区间内的所有数字,第二个(5-8),等等。

// numbers and intervals must be in ascending order
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
// 1-4 , 5-8 , 9-12 , 13-16 , 17-20
var intervals = [4, 8, 12, 16, 20];

numb.sort(function (a, b) {
  return a - b;
});

var groups = [];
var j = 0;
for (var i = 0; i < intervals.length; i++) {
  var group = [];
  while (numb[j] <= intervals[i]) {
    group.push(numb[j]);
    j++;
  }
  groups.push(group);
}
console.log(groups);

输出:

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

编辑:阅读有关计算基于阵列中的最大数量的间隔注释之后。

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

numb.sort(function (a, b) {
  return a - b;
});

var max = numb[numb.length - 1];
// Five groups based on the max value of the array
var increment = max / 5;
var groups = [];
var j = 0;
for (var i = increment; i <= max; i += increment) {
  var group = [];
  while (numb[j] <= i) {
    group.push(numb[j]);
    j++;
  }
  groups.push(group);
}
console.log(groups);

输出:

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


Answer 2:

 // 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

它仅适用于正数。



Answer 3:

代码:假设sortedNumb不是空的:)

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

while (i < sortedNumb.length)
{
    if (sortedNumb[i] >= lastfirstValueInArray+4 || (sortedNumb[i]%4 == 1 && sortedNumb[i] != lastfirstValueInArray)) 
    {
        j++;
        lastfirstValueInArray = 1+j*4;
        groups[j] = [];
    }
    groups[j][groups[j].length] = sortedNumb[i];
    i++;
}

console.log(groups);

输出:

[Array[6], Array[7], Array[3], Array[2], Array[2]]

编辑

您似乎想要为4组,如果你想N ,只需创建一个函数把它作为参数,并更换所有4通过N代码=)



文章来源: Javascript Array grouping category