在JavaScript中进行分区 [英] Partitioning in JavaScript

查看:174
本文介绍了在JavaScript中进行分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下数组:

arrayAll = [1,2,3,4,5,6,7,8,9]

是否有一个软件包可以进行分区以获取:

Is there a package that enable to do partitioning to obtain :

arrayALLPartionned = [[1,2,3],[4,5,6],[7,8,9]]

我可以看到如何使用for循环执行此操作,但如果存在,则会欣赏预制功能。

I can see how to do this with a for loop but would appreciate a "pre-made" function if existing.

推荐答案

如果使用 Underscore.js ,您可以使用 groupBy() values()

If using Underscore.js, you can implement this with groupBy() and values()

function partition(items, size) {
    var result = _.groupBy(items, function(item, i) {
        return Math.floor(i/size);
    });
    return _.values(result);
}

(这不那么难看。)

(This is less ugly in CoffeeScript.)

jsFiddle: http://jsfiddle.net/MW3BS/

jsFiddle: http://jsfiddle.net/MW3BS/

这篇关于在JavaScript中进行分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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