将原始类型的Javascript数组分成多个部分 [英] Partition Javascript array of primitive types into multiple parts
问题描述
我希望能够像这样对原始类型的无序数组进行分区:
I want to be able to partition an unordered array of primitive types like so:
var array = [102,103,104,201,203,204,303,301,302,405,406,408,101];
=>
newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]]
根据第一个整数将数组分割成段。
The array gets partitioned into segments based upon the first integer.
数组将根据类似于此表达式的内容进行分区:
The array would be partitioned based on something similar to this expression:
array[i]/100|0 === j;
其中j可以是1,2,3或4。
where j could be 1,2,3, or 4.
例如。 405/100 | 0 === 4 //分区到以4开头的数组。
有谁知道一种方法,我可以根据第一个数字有效地过滤这个数组?
Does anyone know of a way that I could efficiently filter this array into sections based on the first number?
我知道我可以使用lodash分区函数与集合,但我需要初始数组才能成为速度的原始类型。即使这样,分区也只会将数组分成两部分。
I'm aware that I could use the lodash partition function with collections, but I need to inital array to be only primitive types for speed. Even then, the partition would only part the array into 2 parts.
提前致谢!
推荐答案
您可以使用lodash函数链接
You may use lodash function chaining like
var array = [404,101,102,103,104,201,203,204,303,301,302,405,406,408];
var newArray = _(array)
.groupBy(function (x) { return x / 100 | 0; })
.values()
.value();
这篇关于将原始类型的Javascript数组分成多个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!