0

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);
3
  • 1
    Is your expected result 1 or something else (like 9 or 4)? Commented Apr 24, 2022 at 6:43
  • If you are looking for exact same number, then use like: arr.filter(x => x == 7).length to get the count. answer will be 1; and for testing purpose, try adding one more 7 in arr variable. count will be 2. Commented Apr 24, 2022 at 6:48
  • stackoverflow.com/questions/2903542/… gives methods for counting how many characters appear in a string. Use one instead of the code which uses 'includes'. Commented Apr 24, 2022 at 6:52

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.