I have an empty array which i try to add unique objects (checkedAccounts) in a for loop. I log the unique objects in a console so i can confirm they are all unique. funny thing is, after the loop my array repeats the same value of the last index.
So in a case of adding [1,2,3] to the empty array inside a for loop, instead of getting [1,2,3] i get [3,3,3]
find below my 2 different approaches that didnt work
//Approach 1
let finalAccounts:any[] = [];
let item:any = this.productModel;
let i:number = 0;
for(i = 0; i < checkedAccounts.length; i++){
item.accountNo = checkedAccounts[i].accountNo;
item.accountName = checkedAccounts[i].accountName;
item.accountType = checkedAccounts[i].accountType;
finalAccounts[i] = item;
console.log('item in loop ' + i, item);
console.log('Final acounts in loop ' + i, finalAccounts);
}
console.log('Final Accounts', finalAccounts);
//Approach 2
let finalAccounts:any[] = [];
let item:any = this.productModel;
for(let account of checkedAccounts){
temp.accountNo = account.accountNo;
temp.accountName = account.accountName;
temp.accountType = account.accountType;
finalAccounts.push(temp);
console.log('temp'+checkedAccounts.indexOf(account),temp);
}
let finalAccounts:any[] = [];what is this syntax?let item:any = this.productModel;inside for loop which solves your issue . you cant share instance