Problem of Restricting Array to Single Element at Once

I seem to be facing an issue with a seemingly straightforward function that creates an array - and I'm unable to pinpoint the root cause of the problem. It's probably something simple, but for some reason, it eludes me.

Here is the function in question:

private onSelection(selection)
{
    if (selection)
    {
        const selectionsArray = [];
        selectionsArray.push(selection);
        console.log(selectionsArray);
        console.log(selectionsArray.length);
        return selectionsArray;
    }
}

The "selection" is passed through a checkbox, like this:

<md-checkbox (click)="onSelection('A')">A</md-checkbox>
<md-checkbox (click)="onSelection('B')">B</md-checkbox>
<md-checkbox (click)="onSelection('C')">C</md-checkbox>

Currently, irrespective of which checkboxes are clicked, my array only contains one item at all times, as evident from the length being constantly 1 when logged to the console. What could I possibly be overlooking here? Why isn't the array expanding to accommodate multiple selections being added?

Answer №1

When handling your onSelection, it is important to note that the existing array gets reset each time before adding a selected element. To prevent this from happening, it is advisable to initialize your array outside of the onSelection function.

Here is a suggestion: You might consider eliminating the if (selection) condition in your code as it will always be true. Instead, check if the selected element already exists in your selectionsArray before adding it. This way, you can avoid any duplicate entries in your selectionsArray. Additionally, you should remove the const declaration for your selectionsArray since it serves no meaningful purpose.

const selectionsArray = [];
private onSelection(selection)
{
  if (selection)
  {
    selectionsArray.push(selection);
    console.log(selectionsArray);
    console.log(selectionsArray.length);
    return selectionsArray;
  }
}

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

What is the importance of having Actions and Reducers in Redux?

I am trying to grasp the reasoning behind the design of Redux. For instance, let's consider a scenario where I have a store with a list of todos. If the store is represented as an object like this: {1: todo1, 2: todo2, 3: todo3, ...}* And we enca ...

Can you explain how to add a string array to an HTML div using AJAX?

My output consists of a string array that comes from PHP JSON. I am trying to display this output in an HTML div tabcontent, but I'm unsure of how to achieve this. Below is a snippet of my code - can anyone help me with this? [{"id":"1","p_name ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

Having trouble with the Javascript denial of submit functionality?

I'm dealing with an issue in my code where form submission is not being denied even when the input validation function returns false. I can't figure out what's causing this problem. <script> function validateName(x){ // Validati ...

Is there a way to mimic a synchronous while loop using promises?

array.forEach( element => { let offset = 0; let maxRows = 100; while (maxRows === 100){ getUrls(offset*100, element) // DB query that retrieves rows, more on this below .then( //code ) offset++; ...

Fetching data from an array object in a JSON API using React.js

I am facing the challenge of retrieving data from a JSON API where the data is stored in an Array with object types, and it contains timestamps. My goal is to convert these timestamps into time format using JavaScript. Take a look at the code snippet belo ...

Chrome's rendering of CSS flex display shows variations with identical flex items

I am facing an issue with my flex items where some of them are displaying incorrectly in Chrome but fine in Firefox. The problem seems to be with the margin-right of the rectangle span within each flex item, along with the scaling of the text span due to f ...

Populating form inputs with FCKeditor content prior to form submission

Currently, I am working on resolving an issue with a form on a website that relies on javascript for field validation. It has come to my attention that certain fields utilize fckeditor, causing the form field values to remain unset until the submit button ...

What is the best way to retrieve multiple variables using Express.js on Node.js?

Trying to fetch Form data from an HTML page to a Node Js server. The HTML file is named index.html <body> <nav> <ul> <li> <a href="#" class="button add">Add Product</a> <div class="dialog" style="displ ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

What is the best way to apply CSS to a specific row in AngularJS?

I am currently developing a to-do list using AngularJS. It's almost completed but I have a question regarding highlighting the entire row when in editing mode by adding a CSS class "yellow". Unfortunately, I'm unsure how to achieve this. Additio ...

What is the best way to access a child element from a parent element in HTML?

I am facing an issue with my HTML page where I have an element that opens a bootstrap modal and a button inside the modal launch div that displays an alert when clicked. The problem arises when the alert is displayed, and upon closing it, the modal also ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Issue encountered with Vue.js build configuration not being loaded while running on the build test server

I am working on a Vue 2 project and facing an issue with loading configuration settings from a config.json file. My router\index.ts file has the line: Vue.prototype.$config = require('/public/config.json') The config.json file contains imp ...

Condensing an Array of Objects into a solitary result

Hey there, I'm currently exploring the most efficient method to accomplish a task. The data I am dealing with looks something like this: [ { name: 'email.delivered', programme: 'Email One', timestamp: 2022-03-24T18: ...

Determine the Angular object's type even if it may be undefined

Currently diving into Angular and looking to create a method that can determine if an object is of type Dog (identified by a woof property). This is the code snippet I have put together so far: export class SomeClass { public animal?: Dog | Cat; ... ...

Creating a clickable button that directs users to a webpage I designed as well

As part of my learning process, I am in the midst of creating my own website. My goal is to enhance user experience by enabling them to click on a button and seamlessly transition from one page to another. In my quest for knowledge, I have scoured the int ...

Transforming the CanvasRenderer into a WebGLRenderer

I'm interested in implementing a visual effect similar to the one demonstrated in the example here: To achieve this, I want to modify the renderer to use WebGLRenderer instead of CanvasRenderer by changing: renderer = new THREE.CanvasRenderer(); to ...

What is the process for implementing token authentication within headers using an interceptor, especially when the token may be null?

In my Angular13 application with OAuth authentication, I am encountering issues when trying to add the token for all services. I have been unsuccessful in managing the undefined token. Despite trying various techniques to retrieve the token, I always enco ...