本文介绍了如何将数组分为n组? (分解或_.partition数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组= [0,1,2,3,4,5,6],我想根据除以3后的提示,将其划分"为3个数组.

Let's say I have an array = [0,1,2,3,4,5,6] and I want to "partition" it into 3 arrays, based on reminder after division by 3.

所以基本上我想要这样的东西:

so basically I'd want something like:

_.my_partition([0,1,2,3,4,5,6], function(item) {return item % 3;})
// [[0,3,6], [1,4],[2,5]]

(如果ti有帮助,我可以使用下划线,下划线...)

(I can use lodash, underscore, if ti helps...)

推荐答案

有多种方法可以做到这一点:

There are multiple to do this:

I.正常功能

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

myArray = [1,2,3,4,5,6,7,8,9,10];
partition(myArray, 3);

II.添加原型方法

Array.prototype.partition = function(n) {
    var result = _.groupBy(this, function(item, i) {
        return Math.floor(i % n);
    });
    return _.values(result);
}

myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.partition(3)

创建_.partitionToGroups方法

_.partitionToGroups = function(items, n) {
    var result = _.groupBy(items, function(item, i) {
        return Math.floor(i % n);
    });
    return _.values(result);
}

myArray = [1,2,3,4,5,6,7,8,9,10];
_.partitionToGroups(myArray, 3);

这篇关于如何将数组分为n组? (分解或_.partition数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:33