Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console log elements with upper case in an array

I am trying to log to the console the upper case element however, the console throws this error each time: TypeError: arrayNames[i].toUpperCase is not a function

var hello = "Hello, ";
var arrayNames = [];

function greet(name) {

  if (name == null) {
console.log(hello + "my friend");
  }

  //Requirement UpperCase
  arrayNames.push(name);
  for (var i = 0; i < arrayNames.length; i++) {
if (arrayNames[i] === arrayNames[i].toUpperCase()) {
  console.log(hello.toUpperCase() + arrayNames[i].toUpperCase());
}
  }
  //Requirement last element

  if (arrayNames.length > 1) {
var lastElement = arrayNames.pop();
console.log(hello + arrayNames + " and " + lastElement);
  }
  else {
console.log(hello + arrayNames);
  }

}

greet(["James", "Julie", "BEN"]);
like image 231
eyedfox Avatar asked Sep 12 '26 06:09

eyedfox


2 Answers

You are using toUpperCase on an array.
The problem is the line:

arrayNames.push(name);

You are creating a multidimensional Array.
Use

arrayNames = name;

instead.

like image 155
Peter G. Avatar answered Sep 14 '26 23:09

Peter G.


You are creating array of array by this

arrayNames.push(name)

Instead do this

arrayNames = name

Which will simply refer to the same array name.

toUpperCase() function can only be called on a string and not an array.

See modified code bellow:

var hello = "Hello, ";
var arrayNames = [];

function greet(name){
  if(name==null){
    console.log(hello + "my friend")
  }
  //Requirement UpperCase
  arrayNames = name; // NOTICE THE CHANGE HERE
  for (var i = 0; i < arrayNames.length; i++) {
    if(arrayNames[i]===arrayNames[i].toUpperCase()){
        console.log(hello.toUpperCase() + arrayNames[i].toUpperCase());
    }
  }
  //Requirement last element
  if(arrayNames.length>1){
    var lastElement = arrayNames.pop();
    console.log(hello + arrayNames + " and " + lastElement);
  }else{
    console.log(hello + arrayNames)
  }
}

greet(["James", "Julie", "BEN"]);
like image 34
vatz88 Avatar answered Sep 14 '26 22:09

vatz88



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!