Iterate through the entire array without including a specific item

I am struggling with looping through an array of items and applying some code to each item while excluding one specific item (the clicked-on item). I have experimented with using splice, but that method ends up removing the array item completely, whereas I just want to skip over it. Specifically, I am trying to remove a CSS class from each item in the array except for the excluded one.

I have attempted different approaches, such as using splice and also trying conditional statements like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... }, but none of them seem to work successfully.

var array = ["item1", "item2", "item3"];
 var i;
 for (i = 0; i < items.length; i++) {
     if(array[i] is the excluded one){
             skip over}
  else { $(items[i]).removeClass('class');
 }

Although no error messages are being displayed, the code is not functioning as expected.

Answer №1

Utilize the continue

In this particular scenario, we aim to eliminate "item2" and adhere to fixed variable naming/reference:

var items = ["item1", "item2", "item3"];
var i;
for (i = 0; i < items.length; i++) {
  if(items[i] === "item2"){
    continue;
  }

   //$(items[i]).removeClass('class');
   document.write(items[i] + "<br>");
}

Answer №2

Here is a solution that could meet your requirements:

<script type="text/javascript">
    $(document).ready(function(){
        $(".click").click(function(){ //When an element with the class click is clicked
               var items = ["item1", "item2", "item3"];
               var i;
               var itemid = this.id; 
               for (i = 0; i < items.length; i++) { //loop through array
                    if(items[i]==itemid){ //check if current array item matches id of clicked element
                        // This is the clicked item, so do nothing
                    }else{
                        $("#"+items[i]).removeClass('removeme'); // Remove 'removeme' class from other elements
                    }
               }
        });
    });
</script>
<div class="item1 click removeme" id="item1">Test1</div>
<div class="item2 click removeme" id="item2">Test2</div>
<div class="item3 click removeme" id="item3">Test3</div>

Answer №3

Do the elements in the array correspond to the IDs of the elements? If so, make sure to include the "#" indicator in your code.

$('#' + items[i]).removeClass('class')

UPDATE - I just noticed that you named your array "array", but reference it as items in the else block

   var items= ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(items[i] is the excluded one){
               skip over}
    else { $('#' + items[i]).removeClass('class');
    }

I still believe there might be a better approach to this issue - try using consistent names and see if that resolves it.

Answer №4

An elegant approach in functional programming:

const items = ["apple", "orange", "banana"];

// item to exclude
const exclude = "orange";

// using filter to retain only items that are not excluded
const newItems = items.filter((item) => { return item !== exclude } );

// looping through the remaining items
newItems.forEach((item) => { $(item).removeClass("highlight"); });

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

Performing an RxJS loop to retrieve the httpGet response, followed by executing httpPut and httpPost requests based

I am currently working on a UI form that allows users to update or add translation text. To achieve this, I need to create an rxjs statement that will perform the following tasks: Send an httpGet request to the database to retrieve translations in mult ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

Both if and else statements are carrying out code in JavaScript/jQuery

The second if statement is functioning correctly, but the first one always triggers the else statement and never stands alone. This jQuery function is enclosed within another function that is invoked under the "$(document).ready" command. I resorted to u ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

Guide on exporting data from ejs files to a pdf file using pdfkit in a node js environment

Below is the code from my result.ejs file: <div style="width: 50%; margin: auto;"> <table class="table"> <thead> <tr> <th>SUBJECT</ ...

Steps to halt webkit animation within a div located inside a circle:

I have a series of nested circle divs, and I want to give them a pulse animation. The issue is that the text container is within one of these circles, causing the animation to apply to the text as well. I am unable to move the text container due to potenti ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

What are the best methods for rebooting a Node.js project?

As a developer with over 8 years of experience in PHP, I find myself needing to make changes to a live Node.js project, despite not being a Node.js developer myself. The task at hand is simply to change a payment gateway token, which should be a straightfo ...

I am looking to efficiently store and access a collection of form elements, where each group is represented as an array of form elements

I have created a form that consists of groups of elements stored in a database table. I populate the form with data from the table, allowing for edits to be made. Upon submission of the form, changes are saved back to the table based on the submitted form ...

Angular directive for dynamic template inclusion

I am facing an issue while creating a directive that should automatically add tabs and their content. The problem I'm encountering is retrieving the content stored in partials/tabs/tab[x].html. In my code, I have defined a constant named AvailableTab ...

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

Managing the attention on a switch button

I'm struggling to maintain focus on the toggle button after it's been clicked. Currently, when I press the button, the focus jumps to the top of the page. I can't figure out what I'm doing wrong. Below is the code snippet: HTML <b ...

I am encountering an issue with the Node library puppeteer when trying to integrate it with vue.js

While following a YouTube tutorial on utilizing puppeteer in JavaScript, I encountered an issue where the page would not render even if I required the library. The problem seemed to be located right below where I imported my Vue components: <script> ...

Looking for precise information within a Vue b-table by fetching data from an Axios API

My b-table is filled with data from an API hit through Swagger UI, and since there's a large amount of data, I need the search button at the center top of the page to work properly when inputting store code or branch. https://i.stack.imgur.com/l90Zx.p ...