1

I've stuck with basics of JavaScript array. here is my code

let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let new_arr = [];

new_arr = new_arr.concat(arr);
console.log(new_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

new_arr[2].pop();
let sub_arr = [];
sub_arr = sub_arr.concat(arr);

console.log(sub_arr); //output: ['students', 'exams',[{'sub1':80, 'sub2':60}]]

Expected output for sub_arr is ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

I've tried using slice() also. it didn't work. plz help me with this issue.

3 Answers3

0

What you want to do is deep clone.JSON.parse and then JSON.stringify instead will do the job for this.

let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let new_arr = [];

new_arr = JSON.parse(JSON.stringify(arr));
console.log(new_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

new_arr[2].pop();
let sub_arr = [];
sub_arr = sub_arr.concat(arr);

console.log(sub_arr); //output: ['students', 'exams',[{'sub1':80, 'sub2':60}]]
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

You need to deep clone your array, eg.:

const deepClone = (obj) => JSON.parse(JSON.stringify(obj));


let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]];
let new_arr = [];

new_arr = new_arr.concat(deepClone(arr));
console.log(new_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]

new_arr[2].pop();
let sub_arr = [];
sub_arr = sub_arr.concat(deepClone(arr));

console.log(sub_arr); //output : ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B'}]]
Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
0

You could clone a deep copy of an object by using a recursive function as seen below:

const original = [ 'students', 'exams', [
  { 'sub1': 80, 'sub2': 60 },
  { 'grade_sub1': 'A', 'grade_sub2': 'B' }
]];

const clone = val =>
  val == null
    ? null
    : typeof val === 'string'
      ? val
      : Array.isArray(val)
        ? val.map(sub => clone(sub))
        : typeof val === 'object'
          ? Object.fromEntries(Object.entries(val)
            .map(([key, value]) => [key, clone(value)]))
          : val;

const copy = clone(original);

console.log(copy);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132