根据值中的第一个字符将数组分为多个数组 [英] Break array into multiple arrays based on first character in values
本文介绍了根据值中的第一个字符将数组分为多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下javascript数组:
I have the following javascript array:
var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"]
如何创建2个新数组(如果有更多元素,例如3_或4_作为标识符,则要创建更多数组),如下所示:
How can I make 2 new arrays (or more if there are more elements with eg. 3_ or 4_ as identifier) like this:
var 2 = ["2_000001", "2_000002", "2_000003", "2_000004", "2_000005"]
var 1 = ["1_000001", "1_000002", "1_000003", "1_000004", "1_000005"]
我到目前为止:
data.forEach(function (str) {
str_api = str.substring(0, str.indexOf('_'));
console.log(str_api);
a_api.push(str_api);
clean_api = $.unique(a_api);
str_id = str.substring(str.indexOf("_") + 1);
console.log(str_id);
});
它还远没有达到目标.欢迎任何帮助!
Its not really close to the goal yet. Any help welcome!
推荐答案
使用箭头功能
var obj = {};
data.forEach((e, i) => (i = parseInt(e, 10), obj[i] ? obj[i].push(e) : (obj[i] = [e])));
obj;
/* {
"1": ["1_000001","1_000002","1_000003","1_000004","1_000005"],
"2": ["2_000001","2_000002","2_000003","2_000004","2_000005"]
} */
-
(e,i)=>expr
是一个 Function ,它具有两个参数,分别是e
和i
(这里我们只需要i
范围) -
(expr1,expr2)
是两个使用逗号运算符 的表达式 -
expr1吗?expr2:expr3
表示如果expr1
真实,请执行expr2
,否则执行expr3
(e, i) => expr
is a Function which takes two parameters,e
andi
(here we just wanti
scoped)(expr1, expr2)
is two expressions making use of the comma operator,
expr1 ? expr2 : expr3
means ifexpr1
truthy, doexpr2
, otherwise doexpr3
parseInt
将为我们截断,因为_
是无效数字字符parseInt
will truncate for us as_
is an invalid number characterarr.forEach
将函数应用于 Array这篇关于根据值中的第一个字符将数组分为多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文