我有以下javascript数组:
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_作为标识符,则为更多数组),如下所示:
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);
});
它还没有真正接近目标。欢迎任何帮助!
答案 0 :(得分:3)
随时随地生成变量不是一个好主意所以要么使用Object
或Multi Dimensional Array
var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"];
var arr = {};
// Loop through array
[].forEach.call(data, function(inst){
var x = inst.split("_")[0];
// Check if arr already has an index x, if yes then push
if(arr.hasOwnProperty(x))
arr[x].push(inst);
// Or else create a new one with inst as the first element.
else
arr[x] = [inst];
});
代码说明写成注释。
这将导致
{
"2": ["2_000001", "2_000002", "2_000003", "2_000004", "2_000005"],
"1": ["1_000001", "1_000002", "1_000003", "1_000004", "1_000005"]
}
无论如何你都可以使用它。
答案 1 :(得分:2)
使用箭头功能
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
是功能,它带有两个参数,e
和i
(此处我们只想i
作用域)(expr1, expr2)
是两个使用逗号运算符,
expr1 ? expr2 : expr3
表示expr1
真实,expr2
,否则expr3
parseInt
将截断我们,因为_
是无效的数字字符
arr.forEach
将函数应用于数组
答案 2 :(得分:1)
这将创建一个具有属性和所需值的对象。
var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"];
// Initialize a new object
var arrays = {};
// Loop over data
data.forEach(function (str) {
// Get id piece
str_api = str.substring(0, str.indexOf('_') + 1);
// check if existing property for this id, if not initialize new array
if (!arrays[str_api]) {
arrays[str_api] = [];
}
// get value piece
str_id = str.substring(str.indexOf("_") + 1);
// add to that id's array
arrays[str_api].push(str_id);
});
console.log(arrays);
小提琴:http://jsfiddle.net/AtheistP3ace/6e2bLgf5/
输出:
{
2_: ["000001", "000002", "000003", "000004", "000005"],
1_: ["000001", "000002", "000003", "000004", "000005"]
}
编辑:不确定您是否要在属性名称中使用下划线。在您的描述中,您将3_ 4_作为示例,但在代码示例中,您将给出1 2。