JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters.

Check out my code snippet below:

function oppC(){
        var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "computer"];
        for(var i = 4; i < ord.length;i++ ) {
            pEl.innerHTML = ord;
        }
        }

Answer №1

When utilizing your current for loop, it is only examining elements starting from the 5th position onwards. To include all strings longer than 4 characters, you can modify it as follows:

function updatedFunction(){
    var words = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "computer"];
    for(var index = 0; index < words.length; index++){ // Iterating through **all** elements by considering array's zero-indexed structure
        if(words[index].length > 4){ // Checking if the element's length exceeds 4 characters
            pElement.innerHTML += words[index]; // Appending the element to the designated text area
        }
    }
}

Answer №2

It is recommended to utilize the filter function for this task.

Below is the appropriate solution:

function customFunction(){
        var words = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "computer"];
        console.log(words.filter(function(item){
              return item.length>4;
        }));
 }
customFunction();

If you encounter compatibility issues with IE8, please consider using the following approach:

console.log($.grep(words,function(item){
         return item.length>4;
}));

Answer №3

Check out this straightforward code, no need for any JavaScript library

function findLongWords(){
    var words = new Array("Apple", "Two", "Yesterday", "mother", "lol", "car", "computer");
    for(var i = 0; i < words.length; i++) {
        if(words[i].length > 4){
            document.write(words[i]+"<br>");
        }
    }
}

findLongWords();

Answer №4

To ensure that only words with a length greater than 4 are displayed, include an additional if statement within the loop.

function displayWords() {
    var words = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "computer"];
    for (var i = 0; i < words.length; i++) {
        if (words[i].length > 4) {
            output.innerHTML += words[i];
        }
    }
}

Answer №5

Here is a potential solution showcasing how items can be added using CSS.

function addItem() {
        var element = document.getElementById("output");
        var itemList = ["Banana", "Three", "Tomorrow", "father", "haha", "bike", "television"];
        for(var j = 0; j < itemList.length;j++) {
            if (itemList[j].length > 4) {
              element.innerHTML += '<div class="long-item">' + itemList[j] + '</div>';
            }
        }
    }

addItem();
.output-list {
  border: 1px solid #999;
}

.long-item {
  color: #666;
  font-family: Arial;
  border-bottom: 2px solid #999;
  padding: 5px 8px;
}
<div id="output" class="output-list">
</div>

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

Styling pagination using CSS and jQuery

I am looking to display 3 sections in a simple, paginated way that mimics tabs. I am trying to implement the logic where when a pagination item is clicked and has the 'active' class, it should show the corresponding block. However, I am strugglin ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

Having trouble interacting with an element using Selenium in Python

I am trying to figure out how to download an image from Instagram, but I cannot seem to programmatically click on the download button of this page. Even after attempting to use XPath and CSS selector methods for clicking, unfortunately, neither seems to w ...

Transitioning from GeometryUtils.merge() to geometry.merge()

When upgrading from r66 to r67, a message pops up stating: DEPRECATED: GeometryUtils's .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead. The transition doesn't seem straightforward beca ...

Troubleshooting Issues with Google Analytics Internal Link trackEvent Functionality

Using ga.js, I have encountered an issue with tracking internal links on my website. Despite successfully tracking external links and viewing real-time reports for events, the internal links are not being recorded accurately. While testing pages, the tot ...

Different ways to swap table cells using only CSS

Does anyone know how to switch the positions of table cells using only CSS? I have three divs set up like this: #content { width: 1000px; display: table; float: none; vertical-align: top; border: 1px solid red; } #left { float: left; } #ri ...

Having difficulty centering an image in HTML?

I've been struggling to get the image (logo) centered on the top bar! I've tried using align-self: center;, display:block;, but nothing seems to work. It feels like I'm missing something here! Click here for the codesandbox link to view the ...

ng-html-bind for a label with a checkbox

Currently, I have a view that uses the standard bootstrap layout for checkboxes. In this layout, the input is located within the label tag. <div class="checkbox"> <label ng-bind-html="vm.trustedHtml"> <input type="checkbox" ng- ...

Drawing recursive 2D tree fractals using WebGL technology

Attempting to create a binary fractal tree in webgl, but struggling with the branch angles not aligning as desired. The approach involves plotting vertex points into an array, converting it into a float32array, and then utilizing drawArrays(LINE_STRIPE) fo ...

Jquery click event functioning on one page but malfunctioning on another

On one page, the dropdown click function is working, but on another page, even though it's the same component and JavaScript file, it's not working. Here's the component: <li class="nav-item dropdown"> <a clas ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

Applying a margin to a CSS div at the bottom may cause it to not

I'm struggling to achieve the desired outcome with my layout: https://i.stack.imgur.com/CvLFl.png I have successfully replicated the image, but only when my div is not floating on the page (without margin applied and without using position: absolute ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Managing active dropdown menus in VueJS

I'm having trouble figuring out why my navigation menu and method to open subitems on click are not working correctly. [![dropdown_menu][1]][1] new Vue({ el: '#app', data: { //menu "menu_title": "a", "child_ro ...

JavaScript issue with confirm/redirect feature not functioning as expected

A demonstration of JavaScript is utilized for deleting an employee in this scenario... <script type="text/javascript"> function deleteEmployee(employee) { var confirmation = confirm('Are you sure?'); if(confirmation) { ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

Instructions for extracting a specific line from a text file and showing it in an ArrayList on an Android device

I managed to successfully retrieve and display the full content of a text file within a view. Below is an example of the text file format: ## userdetail [William] [Bits] 6th cross road, City house. Rio. <051-22345690>|<002-223456 ...

Issue with font icons not displaying properly on Firefox

In Firefox, the icon is not displaying in the center, but it works fine in Opera. body { height: 100vh; display: grid; place-items: center; } .link { background-color: red; padding: 3px; display: grid; place-items: center; ...

An exploration of dot length in Java: understanding its meaning

Where is the length field defined in Java, such as for array length? Can it be found in the Object class? EDIT: What is the reason behind this field's design? Is it related to security or memory efficiency? ...