JavaScript query: Counting items that begin with a specific letter

I may have a partial solution to the problem. By the end, I just want the conclusion to be, "There are two names that begin with the letter B." I am currently not achieving this with my code below.

let count = 0;
let names = ["Bill", "Julia", "Coral", "Wendy", "Bob"];
for (let i = 0; i < names.length; i++) {
    if (names[i].startsWith("B")) {
    count++;
    }
    console.log("The letter B is at the beginning of " + count + " names");
    }

Answer №1

There are a couple of issues in your code. First, you forgot to add a comma after declaring the variable 'count'. Secondly, the 'console.log()' statement is inside the loop, which means it will be executed multiple times. It should be placed outside the loop.

Here is the corrected code:

var count = 0,
    names = ["Alice", "Bob", "Charlie", "David", "Eve"];

for (var i = 0; i < names.length; i++) {
    if (names[i].startsWith("B")) {
        count++;
    }
}

console.log("Names starting with 'B': " + count);

Answer №2

Utilize the power of RegExp:

const people = ["Sara", "Mike", "Jack", "Emily", "Olivia"];

let startsWithLetter = (people, letter) => { 
  return people.filter(person => {
    let pattern = new RegExp('^'+letter);
    return person.match(pattern);
  });
};

console.log( 
  'There are ' + startsWithLetter(people,"J").length + ' names that start with "J"',
  startsWithLetter(people,"J")
);

Answer №3

<script>
    let counter = 0;
    const names = ["Anna", "Sam", "Brianna", "William", "Brandon"];
    for (let index = 0; index < names.length; index++) {

        //The simple way is to check the first letter
        if (names[index].substring(0)[0].match(/B/ig)) {
            counter = counter + 1;
            console.log(names[index].substring(0)[0] + " is at the beginning of " + names[index]);
        }

    }

    //USUALLY OUTSIDE THE LOOP
    //HERE YOU HAVE ALL THE MATCHED WORDS
    if (counter > 0){
        //Some names start with the letter B
        //Remember to reset it at the end for reuse!
    } else {
        //No matches found...
    }

</script>

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

Unable to extract property from object in context due to its undefined status

Having trouble with the useContext hook in my React app for managing the cart state. Keep getting an error stating that the function I'm trying to destructure is undefined. I'm new to using the context API and have tried various solutions like e ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

Discover the HTML of a different website using Javascript

I'm currently developing a basic webcrawler that will display all the links found on a specified website. Here's what I envision my program doing: - enter a URL: http://www.example.com/ - the program retrieves the HTML source and locates all th ...

Javascript code generated by PHP is failing to run

When you select an option from the dropdown below: <select id='dropdown' name='dropdown' onchange='showChart(this.value)'> <option value="1">Foo</value> <option value="2">Bar</value> </select& ...

Having trouble converting JSON object to regular object?

I'm trying to change a JSON object into a regular object by using this method... var slaobj = eval('('+s+')'); However, it doesn't appear to be working correctly (the `.length' is returning as undefined). What m ...

Highcharts integration with YQL finance data in JSON format

Currently, I am utilizing jQuery and highcharts.js to develop a single line chart on my website that displays historical financial data for any company specified by the user. I have been experimenting with YQL and employed this query to fetch some quotes i ...

Access Vuex Getters in a separate JavaScript file

Within the file /store/user/getters.js: function getLoggedIn (state) { return state.loggedIn } In a different file, router-auth.js, I attempted to access the value (true or false) of getters.getLoggedIn in the following manner: import user from '.. ...

HTML: Ensure that a user fills out a minimum of one text box before submission

<tr><td> First Name: </td><td><input type="text" name="FirstName" required></td> </tr> <tr><td> Last Name: </td><td><input type="text" name="LastName" required> </td></tr> ...

Cloning Div repeatedly instead of the specified quantity

My JSON data contains four sections and I want to clone my html div based on the number of sections. For example, if there are 100 sections in my JSON, I would like the div to be cloned 100 times. Currently, my div is getting cloned with the JSON data app ...

React Issue: Make sure to assign a unique "key" prop to each child element within a mapped list

I encountered the error message below: react Each child in a list should have a unique "key" prop. Here is my parent component code snippet: {data.products .slice(4, 9) .map( ({ onSale, ...

What is the most effective method for managing the onSelect data within the select tag in Angular's reactive form functionality?

Can someone please advise on the best approach to handling this scenario? I have a form with multiple fields, including a select tag. <form [formGroup]="myForm"> <select formControlName="" > <option *ngFor="let c of countries" value ...

Restrict the number of labels on Chart.js exclusively for smaller displays

How to Limit the Number of Labels on a Chart.js Line Chart I am looking for a way to decrease the number of labels on my line chart only when it is viewed on a small device. The solution provided in the previous post suggests using the following code: xAx ...

Plotly: maintaining consistent color scheme across identical elements in multiple graphs

I am currently utilizing Plotly in Javascript to generate some interactive graphs. My goal is to create 2 pie charts that display the distribution of a sale based on A) units and B) value. While I am able to generate the plots successfully, I have notice ...

Adding a KendoColorPicker to a column in a Kendo Grid

When using AngularJS with a Kendo UI grid, I need to have a column that includes a colorPicker. Below is the code I have implemented: $scope.thingsOptions = { sortable: "true", scrollable: "true", toolbar: [{ name: "create", text: "Add Profile ...

How to send variables to a method in a JavaScript modular pattern

I am trying to achieve something similar to the code snippet below. However, it seems to be invalid as it does not allow passing variables, specifically 'min' and 'max' in this case. Is there a way to achieve this functionality? If so, ...

Utilize moment.js to convert an epoch date into a designated time zone

I've spent countless hours searching for a resolution to the issue with moment.js and its inability to accurately display the correct date for a given local time zone. Let me explain my predicament: The flight API I'm utilizing provides me w ...

Creating a promise instance with the axios create method

As someone who is new to TypeScript, I am learning as I go along. One thing I want to do is create an axios instance that can be reused in my code by passing props only where needed. The framework I'm using is React. // Located in a utils folder // a ...

What is the best way to declare module variables in a Node.js environment?

When it comes to declaring variables when requiring modules in nodejs, there are different styles followed by well-known developers. For instance, TJ Holowaychuk uses a style like this: (method1) var connect = require('connect') , Router = req ...

Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work... I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like: ...