-1

function getCapitals(string) {
  var newString = [''];
  for (var i = 0; i < string.length; i++) {
    if (string[i] === string[i].toUpperCase()) {
      newString += string[i];
    }
  }
  return newString;
}

console.log(getCapitals("Madjbaj Avveyhe"));

EXPECTED: ["M", "A"]

RESULT: ["M A"]

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Use [Array.prototype.push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) to add elements to an array – Phil Feb 20 '23 at 00:53

1 Answers1

0

You can use split and filter to get the result in single line

const getCapitals = (str) => str.split('').filter(c => c.trim() && c.toUpperCase() === c);

console.log(getCapitals("Madjbaj Avveyhe"));

You can also use regex here as:

const getCapitals = (str) => str.match(/[A-Z]/g)

console.log(getCapitals("Madjbaj Avveyhe"));
DecPK
  • 24,537
  • 6
  • 26
  • 42