eyedfox
eyedfox

Reputation: 714

execute if the length of the array is greater than 1

If the length of the array is greater than 1 then i would like for the console to log the desired code however the console logs the else statement instead.

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

function greet(name){

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

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

    }

}
//Requirement last element
arrayNames.push(name)

if(arrayNames.length>1){

    var lastElement = arrayNames.pop()
    console.log(hello + arrayNames + " and " + lastElement)
}


else{
    console.log(hello + arrayNames)
}


}

greet(["James", "Garry", "JOSHUA", "steven"])

Upvotes: 0

Views: 2517

Answers (4)

Manh Le
Manh Le

Reputation: 1650

Error is push use to add one element to array.

You should use concat

arrayNames = arrayNames.concat(name)

instead

arrayName.push(name)

Upvotes: 0

Derek
Derek

Reputation: 145

I'm more in the C# world than Javascript, but I think what you've got is a "type" problem. You are calling the greet function with an array of strings. When you push that into your arrayNames, arrayNames becomes an array of an array of strings - that is, each element of arrayNames is itself an array of strings, and there is only one of them because you are only calling greet once.

Instead, try changing greet(["James", "Garry", "JOSHUA", "steven"]) to this and it should work (noting that James will not meet the if condition since he is the first):

greet("James")
greet("Garry")
greet("JOSHUA")
greet("steven")

Or you could get fancy and do a for or foreach loop.

Upvotes: 0

Hitesh Kumar
Hitesh Kumar

Reputation: 3698

You are pushing the whole array into another array as an element.

//Requirement last element
arrayNames.push(name) //[Array[4]]

//change this to 
Array.prototype.push.apply(arrayNames, name)

// if you want to use spread operator do this
arrayNames.push(...name)

Upvotes: 1

You are pushing one item into arrayNames. It happens to be an array but it is ONE array, so arrayNames.length = 1.

Upvotes: 0

Related Questions