Nick Huemmer

16 April 2022

Two Ways to Solve Seven Boom!

Here’s another challeng from Edabit Edabit

Create a function that takes an array of numbers and return “Boom!” if the digit 7 appears in the array. >Otherwise, return “there is no 7 in the array”. Examples

sevenBoom([1, 2, 3, 4, 5, 6, 7]) ➞ “Boom!” // 7 contains the number seven.

sevenBoom([8, 6, 33, 100]) ➞ “there is no 7 in the array” // None of the items contain 7 within them.

sevenBoom([2, 55, 60, 97, 86]) ➞ “Boom!” // 97 contains the number seven.

First, here’s a long, more verbose way to solve the problem with JavaScript:


const numbers  = [35, 4, 9, 37, 57];

function sevenBoom(arr) {
	let filtered = arr
  .join('')
  .split('')
  .filter(x => parseInt(x) === 7)
  .length;
  
  if (filtered >= 1) {
  return 'Boom' } else {
    return 'there is no 7 in the array'}
}

sevenBoom(firstArray) // 'Boom'
sevenBoom(secondArray) // 'there is no 7 in the array'

And here’s a concise version using basically the same methods, but employing arrow syntax and the conditional ternary operator:

const firstArray  = [35, 4, 9, 37, 57];
const secondArray = [1, 2, 5, 9, 25]

const sevenBoom = (arr) => 
arr.join('').split('').filter(x => parseInt(x) === 7).length  >= 1 ? 'Boom!' : 'there is no 7 in the array'

sevenBoom(firstArray) // 'Boom!'
sevenBoom(secondArray) // 'there is no 7 in the array'

What’s going on here? Arrow functions allow us to write more concise code. This means that sometimes the code is easier to read, follow and maintain and takes up less space while doing the same thing as the traditional function declarations.

In this case, we using the same methods and the ternary operator to detemine if there are any sevens in the array, either singly or part of larger numbers like 37, 107, 217 etc. This

First, we use the join method to join all the numbers together in a long string. This will then allow us to separate each individual digit with the split method, creating an array of single digits. Then, we use the filter method to first apply parseInt to convert each digit to an integer (since it was made a string by the join method), and filter out anything that’s not a 7. Next, we apply the .length property to the array to return the length of the array. Lastly, we test to see if the array length is 1 or greater, which indicates that it contains a 7. If it is greater than or equal to 1, we return ‘Boom!’, otherwise we return ‘there is no 7 in the array’.

This is not my solution (it’s from Pustur) but is a very elegant solution to the problem using regular expressions and the test method:

const sevenBoom = arr =>
  /7/.test(arr) ? 'Boom!' : 'there is no 7 in the array';

Very elegant, wish I was clever enough to think of a solution as short as this one.