Determining the occurrence of a specific value within an array using JavaScript

Can you help refine my function? I've created one that counts the number of 7s in an array, but it only counts each element once even if it has multiple 7s. How can I modify it to calculate the total number of 7s in the array without missing any? Please explain the solution in an easy-to-understand manner since I am new to JavaScript.

function sevenBoom(arr){
  debugger;
  let singleElement, string, includeSeven;
  let flag = false;
  let counter = 0;

  for (let i=0; i<arr.length; i++){
    singleElement = arr[i];
    string = singleElement.toString();
    includeSeven = string.includes("7");
    if (includeSeven == true){
      flag = true;
      counter += 1;    
    }   
  }
  if (counter == 0){
    return "There is no 7 in the array";
  }else{
    return `Boom! There are ${counter} 7s in the array...`;
  }
}
arr = [6,7,87, 777, 107777];
sevenBoom(arr);

Answer №1

Transform an array of numeric values into an array of single-character strings:

/**
* @param {string} char - enclose the number you want to find in quotes
* @array {array<number>} array - an array of numbers
*/
function convertToChar(char, array) {...

/*
.string() converts each number to a string
.map() returns those strings as an array of strings
.join('') merges that array of strings into a single string
.split('') then splits that single string and produces an array containing single character strings.
*/
const chars = array.map(num => num.toString()).join('').split('')

Afterwards, filter the array of characters based on a specified number ('7') and return the count:

// Selects only characters that match the given character ('7')
const hits = chars.filter(str => str === char);
return hits.length;

const seven = [0, 100.7, 8, 9, 55, -63, 7, 99, -57, 777];

function convertToChar(char, array) {
  const chars = array.map(num => num.toString()).join('').split('');
  const hits = chars.filter(str => str === char);
  return hits.length;
}

console.log(convertToChar('7', seven));

Answer №2

When dealing with your data

const numbers = [6,7,87, 777, 107777];

If you want to find the occurrences of the number 7 in the array, you can utilize reduce and split in this manner

const countNumbers = numbers.map((num) => {
  return num
    .toString()
    .split("")
    .reduce((acc, current) => (current === "7" ? acc + 1 : acc), 0);
});

The resulting array from the above operation would be

[0, 1, 1, 3, 4]

This means that for the original array [6,7,87, 777, 107777], we obtain [0, 1, 1, 3, 4]

Check out the CodeSandbox link for a hands-on example: https://codesandbox.io/s/lucid-keldysh-9meo3j?file=/src/index.js:38-186

Answer №3

The function has been updated to tally the occurrences of the numeral "7" in each number within the Array.

A Regex pattern, /7/g, is utilized to count the instances of 7 in every string element. For a detailed explanation of this regex, click here.

Within the loop, it tallies how many times "7" appears in each array element and calculates the cumulative total accordingly.

Fiddle in Action

function sevenBoom(arr) {
    let singleElement, string, includeSeven;
    let flag = false;
    let counter = 0;

    for (let i = 0; i < arr.length; i++) {
        singleElement = arr[i];
        string = singleElement.toString();
        const count = (string.match(/7/g) || []).length;
        if (count > 0) {
            flag = true;
            counter += count;
        }
    }
    if (counter == 0) {
        return "There is no 7 in the array";
    } else {
        return `Boom! There are ${counter} 7s in the array...`;
    }
}
arr = [6, 7, 87, 777, 107777];
console.log(sevenBoom(arr));

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

Utilizing Angular's factory and $resource in your project

For my first app using Angular, I have defined my service as: angular.module('mean.testruns').factory('Testruns', ['$resource', function($resource) { return $resource('testruns/:testrunId', { testrunId: ...

The functionality of "#button_1" remains unchanged despite using .click() or .hover() methods

Seems like I made a beginner's error - the #button_1 ID seems to be immune to the jQuery effects of click() or hover(). If someone could spare a moment to check out my JSFiddle, it would be incredibly helpful. It's likely something quite simple ...

How to Use Attributes as Component Parameters in Vue.js

I am currently developing a test Component using Vue.js. I am trying to pass a parameter to be used in my template like this: Vue.component('test', { props: ['href'], template: '<li><a href="{{href}}"><slot> ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Activate the script upon the left-click of the arrow icon

Looking for help with this basic javascript code snippet. $('#about_us').on('click',function() { $('#slider').toggleClass('open'); }); I'm trying to find a way to activate this function by pressing the lef ...

Angular.js ng-repeat directive with an if statement

I've been working on implementing an if statement into a ng-repeat directive, but I'm struggling a bit. Here's the code that is currently working for me: <p ng-repeat="list in lists">{{list[id].title}}</p> What I'm trying ...

Pager.js utilizing Deferred Bindings

I am currently working on using Pager.js to develop a single page application. The structure I have set up is as follows: #word/definition #word/example #word/synonym This means that definition, example, and other elements are divs with page bindings: & ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

Extract a value from a JSON array without using any predefined entities

Can someone help me figure out how to access the values for 2.2.10.60 and "bank overdrafts...." from the array linked below? https://i.sstatic.net/XF3v9.png I attempted to retrieve the values using the following code: var json=chunk.toString(); ...

Utilizing Numpy Arrays for Graph Representation

The data is currently in a specific format: tail head P01106 Q09472 P01106 Q13309 P62136 Q13616 P11831 P18146 P13569 P20823 P20823 P01100 ... Are there any suggestions for converting this data into a graph using a numpy array? I am interested in ca ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

Using a number input with step increments of 0.01 in AngularJS can result in undefined values for specific inputs

An issue arises when using a specific type of input in angularjs (1.6.1) where the values between 9.03 to 9.05 inclusively return undefined. This problem also occurs with other values like 9.62, 9.63, and 17.31. <input type="number" step="0.01" data-ng ...

Encountered ENOENT error while setting up create-react-app

Recently delved into the world of React by taking an online course on Udemy. However, I encountered a sudden issue with my create-react-app and received this error log. Installing packages. This may take a few minutes. Installing react, react-dom, and ...

Unable to populate data to HTML table using AJAX success function

When I use AJAX to filter data in the table, the data is not showing up. Instead, the data on the table disappears. Below is the script code I am using: $(document).ready(function() { $("#inputJenis").change(function() { var key = $(this).val ...

Having trouble retrieving XSRF-TOKEN from cookie in Next.js (React.js)?

When working with Next.js and Laravel 8 backend, I encountered an issue where I couldn't set the XSRF-TOKEN generated by Laravel on my fetch request for login. Despite being able to see the token in the inspect element > application tab > cookie ...

When a user clicks, they will be directed to the specific product page using Angular UI router

On my homepage, I have a JSON feed where all the products are displayed. When clicking on a specific product image, I want it to redirect to a separate page showing only that particular product. I understand that changes need to be made in the singleproduc ...

Various web browsers are displaying distinct jQuery errors when executing the code

I'm currently working on validating and uploading images using multiple accept inputs with the help of jQuery, AJAX, and PHP. I have successfully added a validation function that is working correctly, but the form is not submitting. Additionally, Chro ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Exploring the usage of promises with data in VueJS async components

Experimenting with VueJS 2.0 RC and utilizing the fetch API to retrieve data for certain components. Here's a sample scenario: const Component = { template: '#comp', name: "some-component", data: function () { return { basic ...