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?
-
1Copy and paste your code into your question, formatted as code (use the {} icon), and include what you expect the result to be vs what the result actually is (precisely, showing the actual data, not a description of the data).blm– blm2015年10月27日 07:21:57 +00:00Commented Oct 27, 2015 at 7:21
-
The slice() method returns a shallow copy of a portion of an array into a new array object.Grundy– Grundy2015年10月27日 07:43:53 +00:00Commented Oct 27, 2015 at 7:43
2 Answers 2
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));
answered Oct 27, 2015 at 7:31
Özgür Kaplan
2,1562 gold badges16 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Grundy
only when in
get_field_options not circular referencelang-js