Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this JavaScript problem possible without loops?

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]);
        }
    }
}
like image 487
João Pacheco Avatar asked Mar 25 '26 15:03

João Pacheco


1 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));
like image 77
CertainPerformance Avatar answered Mar 27 '26 04:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!