Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string.

Suppose I have two checkboxes labeled: label1 and label2, my array looks like this: ['label1','label2'].

The expected outcome should be "Filtered by: Label1, Label2" but instead, I end up with

Filtered by: Label1,Label2, Label1,Label2

I believe the issue lies within the for loop where I construct the string, as the array appears correct

let topLabel = jQuery('.industry-filter').data('selected-text') + ' ';
let termsName= ['Industry', 'Category']
if(termsName.length){
  for(var j = 0; j < termsName.length; j++){
    if(j == termsName.length - 1){
      topLabel += termsName;
    }else{
      topLabel += termsName+', ';
    }
  }
}else{
  topLabel = jQuery('.industry-filter').data('text');
}

$('.industry-filter').text(topLabel);

If you'd like to see the problem in action, check out this pen: https://codepen.io/anon/pen/pqjYxL

Answer №1

In order to retrieve specific elements, you should utilize the index.

When you don't use an index, you end up assigning the entire array.

let primaryLabel = jQuery('.industry-filter').data('selected-text') + ' ';
let categories= ['Industry', 'Category']
if(categories.length){
  for(var i = 0; i < categories.length; i++){
    if(i == categories.length - 1){
      primaryLabel += categories[i];
                           ^^^
    }else{
      primaryLabel += categories[i] +', ';
                           ^^^
    }
  }
}else{
  primaryLabel = jQuery('.industry-filter').data('text');
}

$('.industry-filter').text(primaryLabel);

Answer №2

Make sure to access a specific element by its index.

if(j == termsName.length - 1){
  topLabel += termsName[j];
}else{
  topLabel += termsName[j]+', ';
}

An alternative, more concise approach is to utilize the join method.

if(termsName.length){
   topLabel += termsName.join(',')
}

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

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

The components declared in the index file are rendered on every route throughout the React application

I'm a beginner with React and I'm using react-router version 6.0.2. My issue is that I created a component for the router and then called this component in the index file. However, when I add another component to the index file, it gets rendered ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Error: There was a syntax issue when trying to parse JSON due to an unexpected identifier "object" in the anonymous function

I'm having trouble understanding why there was an issue parsing this file: { "t": -9.30, "p": 728.11, "h": 87.10 } This is the javascript code I used: <script type="text/javascript"> function verify() { $.get("http://....file.json", funct ...

Disabling the visibility of elements through a transparent sticky-top menu

I'm having an issue with my website design. I have a gradient background and a sticky-top menu on the site. The problem is that when I scroll down, the content appears through the menu, which is not ideal. I don't want to apply the same gradient ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

Creating Dynamic Components in ReactJS with Conditional Rendering

Currently, I'm using an if-else statement to show different content based on whether Firestore is ready and the user is logged in. However, I am facing an issue where the firebase.auth.uid is returning as undefined even though it is correctly connecte ...

Trouble with radio button selection in Pyppeteer, puppeteer, and Angular JS

I am struggling to select the 'fire' option in a radio button within a div element using Pyppeteer. Despite multiple attempts, I have not been successful. Here is the structure of the div with the radio button: <div _ngcontent-xqm-c396=" ...

Edit esri pop-up template

Can I customize the popupTemplate in Esri to match my design? I currently have a popupTemplate set up like this: popupTemplate: { content: [{ type: "fields", fieldInfos: [{ fieldName: "Name" ...

Is it possible to modify variables in the controller when the route is changed?

My application utilizes a template and several views that are dynamically rendered based on their route: popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

Tips for avoiding the display of concealed forms on a webpage

Hey there, I'm just starting out with html forms and currently experimenting with Jquery to hide forms upon loading the page. However, I've encountered an issue where some forms briefly appear before hiding after the page finishes loading. Here& ...

Unable to access a text file while executing a javascript file as a systemd service

Running a javascript file using node on a Raspberry Pi at startup automatically through a systemd service has been giving me some trouble. I followed a guide similar to this one to set it up. When I manually run the javascript file by entering the comman ...

What is the extent of an object within a JavaScript Array?

Exploring scopes in JavaScript has led me to an interesting discovery when calling functions from an array. In the example below, I experiment with three different scopes: one bound to an Object named foobar, one bound to window, and a third one which po ...

Combining arrays of objects that contain nested arrays of objects using JavaScript along with libraries such as lodash or Underscore

Attempting to combine two arrays of objects using the lodash JavaScript library, however, encountering an issue where the Subcategories property containing another array is not being merged. Here are the arrays to be combined: var menu1 = [ { "PageNa ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...

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 ...

Activate a change or response when the input value in Javascript is altered

Currently, I am working on a small project using JQuery and facing an issue when trying to remove error classes from HTML elements. To handle the removal of the error classes, I am utilizing $('selector').on('input') event to target th ...

Using jquery, transform json data into html table format

As a beginner in the realm of coding, I am currently experimenting with extracting data from my json file and transforming it into an HTML table. My tool of choice is the Atom code editor, and I am attempting to use JavaScript, specifically jQuery, to it ...