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?

  • 1
    Copy 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 Oct 27 '15 at 07:21
  • [The slice() method returns a shallow copy of a portion of an array into a new array object.](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) – Grundy Oct 27 '15 at 07:43

2 Answers2

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));
Community
  • 1
  • 1
Özgür Kaplan
  • 2,106
  • 2
  • 15
  • 26
0

Yet another way, use map and concat functions

var op_arr = selectlist.map(function(el){
    return get_field_options.concat(el);
});
Grundy
  • 13,356
  • 3
  • 35
  • 55