将处于10的倍数的相同范围内的数组值分组 [英] Group array values that are in the same range of multiples of 10

查看:82
本文介绍了将处于10的倍数的相同范围内的数组值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,例如:

var arr = [2,4,7,11,25,608,65,109,99,100,504,606,607];

我需要进行设置,以便将其下面10的倍数和上面10的倍数范围内的每个值组合在一起.

I need to make it so each value that is within range of its multiple of ten below and and multiple of ten above it is grouped together.

例如,2,4,7在0到10之间,因此它们必须在一起. 11个会单独出现在其组中,例如25,65等. 606,607,608将在一起.

For example, 2,4,7 are between 0 and 10 so they must be together. 11 would be alone in its group, like 25,65 etc. 606,607,608 would be together.

上面的数组应变为:

[ [2,4,7],[11],[25],[65],[99],[101],[504],[100,109],[606,607,608] ]

我已经考虑了几个小时,但还没有提出任何建议.确实值得一提的是,这真的很糟糕,但是到目前为止,我正在使用Math.round( http://jsfiddle.net /40napnyx/2/)

I've been thinking about it for a couple of hours and I wasn't able to come up with anything yet. It's really bad not much worth mentioning but so far I'm playing with Math.round (http://jsfiddle.net/40napnyx/2/)

我想添加另一个问题(尽管如果实际答案中不包含该新问题的解决方案,尽管我不会根据此问题选择正确的答案).

I'd like to add another issue (although I will not pick the correct answer based on this if the actual answers don't include the solution of this new problem).

该数组可能包含带有字母的值.这些值应按字母顺序位于同一组中(仅使用第一个字母来确定顺序).该组应该是结果数组中的最后一个值.

The array may contain values with letters. Those values should all be in the same group, in alphabetical order (only the first letter is taken to determine the order). This group should be the last value in the resulting array.

例如 var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4];

将会是[[2,4,7],[11],[25],['a3','bzy4', 'j']]

推荐答案

这是一个通用函数:

function groupBy(ary, keyFunc) {
  var r = {};
  ary.forEach(function(x) {
    var y = keyFunc(x);
    r[y] = (r[y] || []).concat(x);
  });
  return Object.keys(r).map(function(y) {
    return r[y];
  });
}

// usage:

var arr = [2,4,7,11,25,608,65,99,101,504,606,607];

g = groupBy(arr, function(x) { return Math.floor(x / 10) });

document.write(JSON.stringify(g));

对于奖金问题,只需两次申请groupBy:

For your bonus question, just apply groupBy twice:

    function groupBy(ary, keyFunc) {
      var r = {};
      ary.forEach(function(x) {
        var y = keyFunc(x);
        r[y] = (r[y] || []).concat(x);
      });
      return Object.keys(r).map(function(y) {
        return r[y];
      });
    }





var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4'];
g = groupBy(arr, isNaN);

g = [].concat(
  groupBy(g[0], function(x) { return Math.floor(x / 10) }),
  [g[1].sort()]
);
          
document.write(JSON.stringify(g));

这篇关于将处于10的倍数的相同范围内的数组值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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