JavaScript issue: Looping to add unique items to an array results in repeated values

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);
}

Answer №1

It is crucial to make sure that a new version of the item is generated with each loop iteration. By utilizing the syntax provided below, we can produce a shallow duplicate. Give this a try:

for(i = 0; i < checkedAccounts.length; i++){
    let item:any = {...this.productModel};
    item.accountNo = checkedAccounts[i].accountNo;
    finalAccounts.push(item);
}

Answer №2

It's important to keep each instance independent when iterating through a foreach loop and pushing items to an array.

A few key points to note:

1) Avoid using any unless absolutely necessary. Instead of

let item:any = {...this.productModel}
, you can achieve the same functionality with let item:any = {}.

2) The recommended approach is to use TypeScript interfaces for type checking.

Sample Code:

finalAccounts: IntTest[] = [];

export interface productModel {
  accountNo: string;
  address?: string;
}

for (i = 0; i < checkedAccounts.length; i++) {
  let item: IntTest = {
    accountNo: checkedAccounts[i].accountNo
  };
  finalAccounts.push(item);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a concealed form or Unveiling a popup dialog

What is the most effective way to display a simple form on an HTML page with a save button that calls a web method? I'm currently contemplating between the following options: Reveal a hidden <div> containing a form with the same functionality ...

Using JavaScript/JQuery to Access an External SQLite Database

Is there a way to incorporate my own SQLite database into a website using JavaScript and JQuery? I've searched for examples but have yet to find any helpful articles on the topic! ...

The unexpected outcome of ambient light in Three.js

Within the code snippet below, I am displaying some cubes and illuminating them with a PointLight and AmbientLight. Strangely, when the AmbientLight is set to 0xffffff, it changes the side colors to white regardless of their assigned colors. The point ligh ...

Can you explain the distinction between init() and window.init()?

After reviewing the recipe on how to connect an AngularJS frontend with a Google Cloud Endpoints backend, I still have questions about the AngularJS and Cloud Endpoints initialization process. The relevant section in question is as follows: Appendix: Tips ...

Fade image and background using Jquery on click event

I've been browsing various sources and utilizing different techniques I've come across (primarily on this platform) to guide me in my progress so far. However, I fear that I may have unintentionally backed myself into a corner by choosing an inco ...

Tips for preventing duplicate array elements from repeatedly appearing in smarty nested foreach loops

There are two arrays in play: $data.applicable_states Array ( [applicable_states] => Array ( [0] => 1 [1] => 3 [2] => 4 ) ) and the other array is called all_states Array ( [0] => Ar ...

Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far: when('/admin', { templateUrl: &ap ...

AngularJS -> Choice for specifying user's decimal format and limit restrictions

Is there a way to use AngularJS to dynamically limit user input to numbers between 0 and 1 with hundredths? For instance, if a user types 0, it should be converted to 0.00; if they type 1, it should become 1.00. I already have a JavaScript function for lim ...

What are some methods for creating a span element that cannot be edited?

I'm having trouble with making a span inside an iframe non-editable. I've tried using pointer-events, contenteditable, and everything else, but nothing seems to work. Can someone please help me out? $('#tokens-menu-list').on('cl ...

how to extract json information from a web address with jquery

I want to extract json data from the following URL: Specifically, I am looking for the value associated with "USDAED" and I need to assign it to an input. { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"htt ...

Using Angular2 to bind HTML markup to a boolean flag and trigger a method when the flag is set

I'm currently developing a solution for Angular 2 Bootstrap Datepicker to automatically close when a user clicks outside of it. My current approach involves tracking external clicks and updating a boolean flag as shown below: @Component({ select ...

display data labels within the chart - utilizing the power of angular.js in conjunction with chart.js

My goal is to display the chart's information without requiring the user to hover over any part of the chart. I am utilizing Chart.js with Angular.js I have the same question as this one posted here: question here! html code: <div class="wrapper ...

What is the best way to transform this code into a JavaScript string that can be evaluated at a later time?

I need a way to save this snippet of JavaScript code, make some modifications to it, and then evaluate it at a later time. Unfortunately, the online converter I tried using didn't produce the desired outcome. Original Code $Lightning.use("c: ...

Can you explain the significance of using curly braces in Javascript coding?

I came across the following code snippet on the page https://nodejs.org/api/modules.html: { }. Specifically, this line caught my attention: const { PI } = Math; Is there a specific term for this syntax? I'd like to learn more about it and understand ...

What is the best way to convert JSON data into a string array and showcase the results?

Recently, I've been exploring the fetch API to retrieve some data. After successfully fetching the data and displaying the response using console log, I now face a challenge in utilizing this information. The API provides me with "result", "id", and " ...

Combining two 2D numpy arrays

I am attempting to combine two 2D numpy arrays using the np.concatenate function. Here is my code: import numpy as np arr = np.array([[]]) #initialize empty 2D array a = np.array([[0.0012, 0.032, 0.039, 0.324]]) b = np.array([[1, 0.2, 0.03039, 0.1324]]) ...

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

The sticky position is malfunctioning even when there is no parent element with the overflow hidden property

// observer for feature section let featuresSection = document.querySelector('#featuresSection'); let callbackFeature = (items) => { items.forEach((item) => { if (item.isIntersecting) { item.target.classList.add("in ...