简体   繁体   中英

generating multidimensional dynamic javascript array

I am trying to generate n arrays with a for loop and push an extra element from another array of n using for loop to each of these arrays.

var userlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];

var selectlist = ['c', 'f', 'k'];

get_field_options = userlist.filter(function (el) {
    return selectlist.indexOf(el) < 0;
});

var selectlen = selectlist.length;
var op_arr = new Array();

for (var i = 0; i < selectlen; i++) {
    op_arr[i] = new Array();
    op_arr[i] = get_field_options;
    op_arr[i].push(selectlist[i]);
    console.log(op_arr[i]);
}

here is my working fiddle .

but its adding items to same array each time. what I am doing wrong?

this line op_arr[i] = get_field_options; makes your arrays reference to the same object.

You need to clone get_field_options to get a new array. One simple way to clone is to use JSON.stringify like this.

op_arr[i] = JSON.parse(JSON.stringify(get_field_options));

Yet another way, use map and concat functions

var op_arr = selectlist.map(function(el){
    return get_field_options.concat(el);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM