JavaScript 中的分区 [英] Partitioning in JavaScript

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

问题描述

请考虑一个数组,例如:

Please consider an array such as :

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);
}

(这在 CoffeeScript 中没有那么难看在 CoffeeScript.)

(This is less ugly in CoffeeScript.)

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

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

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