0

In the below code I'm making a new array named update[] and modifying the Date property of its objects using the updateToCurrentYear() function.

However whenever I try to modify the birthday property in update[], the original array is also updated automatically. How can I avoid this?

function birthdaySearch() {
  var birthdays = [
    { name: 'friend', birthday: new Date('03/25/1999') },
    { name: 'friend1', birthday: new Date('03/28/1999') },
    { name: 'friend2', birthday: new Date('09/25/1999') },
    { name: 'friend3', birthday: new Date('04/04/1999') },
    { name: 'friend4', birthday: new Date('07/05/1997') },
    { name: 'friend5', birthday: new Date('07/25/1998') }
  ];

  var nowDate = new Date();
  nowDate.setHours(0, 0, 0, 0);
  
  var nextMonth = nowDate.getMonth() + 1;
  var nextYear = nowDate.getFullYear() + 1;

  function updateToCurrentYear() {
    let update = [];
    birthdays.forEach(function(detail) {
      //.birthday.setFullYear(2020);
      update.push(detail);
    });
    
    update.forEach(function(update) {
      return update.birthday.setFullYear(nowDate.getFullYear());
    });
    
    console.log(update);
    return update;
  }

  return {
    updateToCurrentYear: updateToCurrentYear,
  }
}

birthdaySearchObj = birthdaySearch();
var current = birthdaySearchObj.updateToCurrentYear();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
tripler25
  • 13
  • 2

2 Answers2

0

arr2=arr1 will be pointing to the same array.
use arr2=arr1.slice() to copy.
(to compare arrays, use: JSON.stringify(arr1)==JSON.stringify(arr2)).

iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

To avoid copying of value, you can make use of spread operator with map here:

function updateToCurrentYear() {
  /*let update = [];
        
   birthdays.forEach( function(detail) {
      //.birthday.setFullYear(2020);
        update.push(detail);
   } );*/
   const update = birthdays.map(b=>({...b}));
        
   update.forEach( function(update) {
      return update.birthday.setFullYear(nowDate.getFullYear() );
   });
   console.log(update);  
   
   return update;
}
gorak
  • 5,233
  • 1
  • 7
  • 19