0

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?

2

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

only when in get_field_options not circular reference
0

Yet another way, use map and concat functions

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.