Is this JavaScript problem possible without loops?

Viewed 205

Currently on a code submission website and it won't let me move forward.

Using this characters array, print to the console every character which name begins with ‘M’. Don’t use any kind of loop, yet.

var filmCharacters = [
       ['Vito', 'Michael', 'Sonny', 'Freddo'],
       ['Mia', 'Vincent', 'Jules', 'Butch'],
       ['Bella', 'Edward', 'Jacob', 'Carlisle'],
       ['James', 'M', 'Moneypenny', 'Felix']
];

my latest try is

for (var i = 0; i < filmCharacters.length; i++) {
    for (var j = 0; j < filmCharacters[i].length; j++) {
        if (filmCharacters[i][j].startsWith('M')) {
            console.log(filmCharacters[i][j]);
        }
    }
}
3 Answers

A for loop is a loop.

If you wanted to make the code hard to understand at a glance, I suppose it would technically be possible to do so without any looping mechanism, such as with recursion:

var filmCharacters = [
        ['Vito', 'Michael', 'Sonny', 'Freddo'],
        ['Mia', 'Vincent', 'Jules', 'Butch'],
        ['Bella', 'Edward', 'Jacob', 'Carlisle'],
        ['James', 'M', 'Moneypenny', 'Felix']
];

const checkArr = arr => {
  if (arr.length) {
    checkSubarr(arr[0])
    checkArr(arr.slice(1));
  }
};
const checkSubarr = subarr => {
  if (subarr.length) {
    if (subarr[0].startsWith('M')) {
      console.log(subarr[0]);
    }
    checkSubarr(subarr.slice(1));
  }
};
checkArr(filmCharacters);

If even that isn't permitted, I suppose the code be really WET.

var filmCharacters = [
        ['Vito', 'Michael', 'Sonny', 'Freddo'],
        ['Mia', 'Vincent', 'Jules', 'Butch'],
        ['Bella', 'Edward', 'Jacob', 'Carlisle'],
        ['James', 'M', 'Moneypenny', 'Felix']
];
const c = filmCharacters;

const check = str => {
  if (str.startsWith('M')) console.log(str);
};
check(c[0][0]);
check(c[0][1]);
check(c[0][2]);
check(c[0][3]);

check(c[1][0]);
check(c[1][1]);
check(c[1][2]);
check(c[1][3]);

check(c[2][0]);
check(c[2][1]);
check(c[2][2]);
check(c[2][3]);

check(c[3][0]);
check(c[3][1]);
check(c[3][2]);
check(c[3][3]);

But this is ridiculous.

var filmCharacters = [
        ['Vito', 'Michael', 'Sonny', 'Freddo'],
        ['Mia', 'Vincent', 'Jules', 'Butch'],
        ['Bella', 'Edward', 'Jacob', 'Carlisle'],
        ['James', 'M', 'Moneypenny', 'Felix']
];

filmCharacters
  .flat()
  .filter(str => str.startsWith('M'))
  .forEach(x => console.log(x));

Based on the prompt saying to not use a loop "yet", I think they just want you to manually console.log the matching characters (for this initial step of the problem).

This is useful so that you know your expected output, which you can use to test against your solution.

console.log('Michael', 'Mia', 'M', 'Moneypenny');

Maybe it's something like this:

console.log(filmCharacters[0][1]);
console.log(filmCharacters[1][0]);
console.log(filmCharacters[3][1]);
console.log(filmCharacters[3][2]);
Related