Home > Blockchain >  Counting a number in given array in javascript
Counting a number in given array in javascript

Time:04-24

I've developed a function that counts the number of "7" in the given array. But the problem is that it counts an element only once if it has multiple 7's. I want to calculate overall number of 7 in the array. Note: Please describe the logic in a simple and easy to understand way as I'm a newbie in 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);

CodePudding user response:

Convert a given array of numbers to an array of single character strings:

/**
* @param {string} char - wrap the number you are seeking in quotes
* @array {array<number>} array - an array of numbers
*/
function findChar(char, array) {...

/*
.string() converts each number into a string
.map() return those strings as an array of strings
.join('') takes that array of strings and converts it into a single string
.split('') takes that single string and splits it and returns an array of single string 
characters.
*/
const chars = array.map(num => num.toString()).join('').split('')

Next, the array of characters is filtered vs the given number ('7') and then return the count:

// Returns only chars 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 findChar(char, array) {
  const chars = array.map(num => num.toString()).join('').split('');
  const hits = chars.filter(str => str === char);
  return hits.length;
}

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

CodePudding user response:

For your data

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

To count the occurence of no. 7 you could make use of reduce and split like so

const countArr = arr.map((item) => {
  return item
    .toString()
    .split("")
    .reduce((acc, curr) => (curr === "7" ? acc   1 : acc), 0);
});

The result for the above countArr would be

[0, 1, 1, 3, 4]

which means for [6,7,87, 777, 107777], we get [0, 1, 1, 3, 4]

CodeSandbox: https://codesandbox.io/s/lucid-keldysh-9meo3j?file=/src/index.js:38-186

CodePudding user response:

I have updated the function to count the occurances of "7" in each number of the Array.

I have made use of a Regex /7/g to count the number of occurances of 7 in each string element. Find the explanation for the regex here.

So inside the loop, it counts the count of "7" in each element in the array and calculates the cumilative total inside the loop.

Working Fiddle

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));

With the same regex, you can count the total number of "7" inside the array in a different way.

Join the array using Array.join() method to generate a single string as the output. Count the total number of "7" inside this string using the same regex.

Working Fiddle

function sevenBoom(arr) {
    const count = (arr.join().match(/7/g) || []).length;
    return count == 0 ? "There is no 7 in the array": `Boom! There are ${count} 7s in the array...`;
}
arr = [6, 7, 87, 777, 107777];
console.log(sevenBoom(arr));

  • Related