I have encountered an issue with populating an empty array with unique objects (checkedAccounts) within a for loop. Despite confirming the uniqueness of the objects through console logging, I am facing the problem of repetitive values in the final array after the loop has completed.
For instance, when attempting to add [1,2,3] to the empty array inside a for loop, instead of obtaining [1,2,3], the result turns out to be [3,3,3]
Below are my two unsuccessful approaches:
//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 accounts 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);
}