Calculate the size of an array after applying a filter operation

I have created an if statement that filters the array based on user input, acting as a search bar for the array.

var filter = userInput.value.toUpperCase();
for (var i = 0; i < myArrayElements.length; i++) {
    if (myArrayElements.toUpperCase().indexOf(filter) != -1)  {
        myArrayElements[i].style.display = 'list-item';
    } else {
        myArrayElements[i].style.display = 'none';      
    }
}

Now, I am looking to determine the length of the filtered array and use it in the global scope.

I attempted to do this within the if statement:

var arrayLength = myArrayElements[i].length;
return arrayLength;

and

console.log(myArrayElements[i].length);

However, both attempts resulted in console errors.

Edit: Nina Scholz's response provided the correct length of the array and presented a great example. Additionally, other responses suggesting the use of .filter() are also valuable. Thank you all!

Answer №1

You might consider using a variable to keep track of the count.

var filter = userInput.value.toUpperCase(),
    count = 0;

for (var i = 0; i < myArrayElements.length; i++) {
    if (myArrayElements[i].toUpperCase().indexOf(filter) != -1)  {
        // ^^^^^^^^^^^^^^^ only if that is really a string!!!
        myArrayElements[i].style.display = 'list-item';
        count++;
    } else {
        myArrayElements[i].style.display = 'none';      
    }
}

Here's an example in action:

function find() {    
    var filter = document.getElementById('search').value.toUpperCase(),
        count = 0,
        myArrayElements = document.getElementsByTagName('li');        

    for (var i = 0; i < myArrayElements.length; i++) {
         if (myArrayElements[i].innerHTML.toUpperCase().indexOf(filter) != -1)  {
              myArrayElements[i].style.display = 'list-item';
              count++;
         } else {
             myArrayElements[i].style.display = 'none';      
         }
    }
    console.log(count);
}
<input id="search" > <button onclick="find()">find</button>
<ul>
<li>test</li>
<li>test-case</li>
<li>42</li>
<li>Test</li>
</ul>

Answer №2

If you want to change the style and filter an array at the same time, you can utilize the .filter() method.

var searchTerm = userInput.value.toLowerCase(),
filterFunction = function(item) {
  if (item === searchTerm) {
    item.style.display = 'block';
    return true;
  } else {
    item.style.display = 'none';
    return false;
  }
}

var filteredItemsCount = myArray.filter(filterFunction).length;

Answer №3

If you want to selectively display elements based on a certain condition, consider using the filter function

The filter() method creates a new array with all elements that meet the criteria specified by the provided function.

var newArray = myArrayElements.filter(function(value, index, array) {
  return value.toUpperCase() === filter;
});
var newArrayLength = newArray.length;

It should be noted that this solution only addresses the filtering aspect and not the logic within the loop. To achieve both, set all elements in myArrayElements as display:none; by default and then execute:

var newArray.forEach(function(value, index, array) {
  value.style.display = 'list-item';
});

Alternatively, you can utilize forEach() from the beginning:

var filter = userInput.value.toUpperCase(),
    count = 0;

myArrayElements.forEach(function(value, index, array) {
  (value.toUpperCase() === filter) ? value.style.display = 'list-item' : value.style.display = 'none';
  count ++;
});

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

PHP failing to recognize ajax request

My PHP script includes a drop-down box, and when I select an option in the dropdown, it triggers an AJAX call to communicate with another PHP script. In Firebug, I can see that the call is being made and the correct parameters are passed. Within my PHP cod ...

How Meteor Handles HTTP Requests in its package.js File

When accessing data from an external source at autopublish.meteor.com, our goal is to gather information about a package's latest release tag either from GitHub or the NPM registry: var version; try { var packageJson = JSON.parse(Npm.require(' ...

"Unlock the full potential of GrapesJs UI with these advanced customization tips

Utilizing Grapesjs in my web application to build web pages. Being a newcomer to GrapesJS, I am unsure about how to personalize the UI using GrapesJs. I simply employ this code. const editor = grapes.init({ container: '#gjs', ...

Combine the information from another cell and add it to the current cell with additional data

Can you help me figure out a way to input numbers and have Google Sheets calculate the change percentage in the same cell? Here's an example: Oct 20 Nov 20 Dec 20 90 100 (+10%) 95 (-5%) I'm hoping to do this without using additional cell ...

The problem with Vue JS static links

I'm currently working with a Vue.js application (v2). I've noticed that if I skip visiting the root of the site, the sub-links do not work properly. For example: Visit: Then go to If I directly visit: I encounter the following error messag ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

Sending an array using the POST method with Ajax

It's puzzling, this seemingly straightforward issue has me stumped. I can't seem to figure out why it's happening, and I haven't come across anyone else experiencing the same problem. Here's the dilemma: I'm sending a POST re ...

Having trouble with Three.js loading gltf file?

I encountered an issue while working on a project that involved using three.js with svelte. The problem arose when attempting to load a 3D model, resulting in a server response of 404 not found. Below is the code snippet I used to load the file(Scene.js) ...

The behavior of AJAX Search varies between the development and production environments

I recently integrated an instant search feature into my application. During testing on the local server, the functionality met my expectations: It filters the list as I type It is not case-sensitive It allows for resetting the search if I delete the inp ...

"Enhancing Event Handling with JQuery Delegate on Internet Explorer

My pop-up menu is set to hide when someone clicks anywhere else on the page. $(window).delegate("body", 'click', hide); While this functionality works in most browsers, I am encountering issues specifically with IE8. Can anyone advise on what m ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

At times, an InvalidArgumentError occurs stating: "The 'handle' parameter must be a string."

I have incorporated 'React-google-login' into my React project and now I am working on an automated test to make sure it functions correctly. try { await driver.get("http://localhost:3000/"); await driver.wait(until.elementLocated(By.xpath(` ...

Retrieve two arrays from PHP files, analyze their differences, and store the variances in a separate array

Looking to merge two php files containing the $_DATA array by identifying and creating a new array (and file) with the differences in keys and values. Some keys are common between the files, while others are unique. The aim is to compare all keys, extract ...

Tips for locating a value that differs from an item in a v-autocomplete box

I am using a v-autocomplete component: <v-autocomplete v-model="fromPrice" :items="listOfFromItems" dense solo label="from" hide-detail ...

Issue with Material UI Textfield error functionality in React.js not functioning correctly

Currently, I am working on a functional component in combination with Material UI. Within this setup, I have constructed a form comprising of 2 textfields. My objective is to activate the error property solely under certain conditions being met. However, t ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

Converting and storing Canvas data as a blob, and then saving the blob as

There is a clickable icon on the page that triggers an action when clicked. Currently, the icon is set as an anchor tag. However, I want to change it to a div like all the other icons in my UI. But for some reason, the following code isn't working. W ...

Component encounters issue with undefined props being passed

Encountering an issue where dummy data is not being passed to a component, resulting in undefined props. Even console.log() statements within the same page are not functioning properly. Can anyone identify what might be going wrong here? import AllPosts fr ...