根据值中的第一个字符将数组分为多个数组 [英] Break array into multiple arrays based on first character in values

查看:63
本文介绍了根据值中的第一个字符将数组分为多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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 and i (here we just want i scoped)
    • (expr1, expr2) is two expressions making use of the comma operator ,
    • expr1 ? expr2 : expr3 means if expr1 truthy, do expr2, otherwise do expr3

      parseInt 将为我们截断,因为 _ 是无效数字字符

      parseInt will truncate for us as _ is an invalid number character

      arr.forEach 将函数应用于 Array

      这篇关于根据值中的第一个字符将数组分为多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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