Click here to Skip to main content
15,895,833 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is going to be a long post, I'm practicing JavaScript functions with loops, and I got a lot of it but I'm stuck with the following cases:

1. A function that returns the number of even numbers of an array.

//======================  EXAMPLE  ========================
isEven([2,4,8,7])
3 // <======  EXPECTED OUTPUT
isEven([1,9,66,"banana"])
1 // <======  EXPECTED OUTPUT
//=========================================================


I wrote this:

function isEven(arr) {
        var count = 0;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] % 2 === 0) {
                count++;
                document.write(count);
            }
        }
    }


But to me it just returns undefined I don't know why.//Solved, I forgot to write the return statement with the right variable in place of document.write. the proper function would be:

function isEven(arr){
    var count = 0;
    for (var i; i < arr.length; i++) {
      if (arr[i]%2 == 0){
            count++
        }
        return count
    }
}



2. I have to create a function which takes an array as argument, with a forEach loop which console.log each element and each index for every iteration inside the function. Also inside the function declare a variable called count, and increment it by one for each iteration then return count.

//======================  EXAMPLE  ========================
looper([2,4,8,7])
4 // <======  EXPECTED OUTPUT
//=========================================================


I wrote this function:

function looper(arr) {
    arr.forEach(function console (item, index){
        var count = 0;
        count++;
        console.log(("I am item ", item, "I am the index ", index));
        return count;
    })
}



But I get the following error:

VM76:5 Uncaught TypeError: console.log is not a function
    at console (<anonymous>:5:17)
    at Array.forEach (<anonymous>)
    at looper (<anonymous>:2:9)
    at <anonymous>:1:1


How is it that console.log is not a function? isn't it prebuilded in every browser?// Solved, Ihad to remove "console" and declare the variable count outside th forEach loop so it keeps the values while looping. Here would be it:
function looper(arr) {
  var count = 0;
  arr.forEach(function(item, index) {
    count++;
    console.log("I am item ", item, "I am the index ", index);
  })
  return count;
}


3. A function that takes an array as an argument and extracts all the strings of the array and puts them into a new array:

//======================  EXAMPLE  ========================
isString([3,55,66,"hello"])
["hello"]"// <======  EXPECTED OUTPUT
isString([3,55,66,"hello","beer",12,{},[],()=>{},"[]"])
["hello","beer","[]"]  // <======  EXPECTED OUTPUT
//=========================================================


I wrote this:

function isString(arr){
    if(typeof arr[i] === 'string'){
     arr2.push(arr[i]);
 }
}


But I get undefined I don't know why.//Solved, again I had to declare the variable outside th forEach loop, and actually declare all variables I use. Here would be the solution:
function isString(arr){
        var arr2 = [];
        arr.forEach(el => {
            if(typeof el === 'string'){
             arr2.push(el);
            }
          });
          return arr2;
        }


4. A function that multiplies all elements of an array by two and returns them in a new array:

//======================  EXAMPLE  ========================
timesTwo([10,10,10])
[20,20,20] // <======  EXPECTED OUTPUT
timesTwo([5, 4,2])
[10,8,4] // <======  EXPECTED OUTPUT
timesTwo([15, 4,2])
[30,8,4] // <======  EXPECTED OUTPUT
//=========================================================


Here is my code:

function timesTwo(array){
    array.forEach(function multiplyByTwo(arrayElement){
        arr2 = [];
        var X = arrayElement * 2;
        arr2.push(X);
    });
    return arr2;
    console.log(arr2);
}


I'm just able to multiply the last element of the array I don't know how to multiply all of them I haven't been able to make it work better.//Solved again, the variable has to be declared outside the forEach loop, otherwise it just keeps the last loop value:
function timesTwo(array){
    arr2 = [];
    array.forEach(function multiplyByTwo(arrayElement){
        var X = arrayElement * 2;
        arr2.push(X);
    });
    return arr2;
    console.log(arr2);
}


5. A function that compares two arrays of the same length and returns the number of matches:


//======================  EXAMPLE  ========================
twoArrays([1,5,80], [10,5,80])
2 // <======  EXPECTED OUTPUT
twoArrays([10,10,10], [10,10,5])
2 // <======  EXPECTED OUTPUT
twoArrays([3,5], [1,4,5])
0 // <======  EXPECTED OUTPUT
twoArrays([3,5], ['3','5'])
0 // <======  EXPECTED OUTPUT
//=========================================================



I was trying to write something but very random code I have no clue on how to get this working.

6. A function that takes a string as an argument, deletes all numbers, puts everything in lowercase and ads spaces:
`
//======================  EXAMPLE  ========================

lowerCaseLetters("An2323t2323one32llo123455Likes567323Play323ing567243G2323a3mes345")
"antonello likes playing games" // <======  EXPECTED OUTPUT
//=========================================================


I know how to put everything in lowercase but I don't know how to remove the numbers other than using .slice() several times with each number, but I believe there has to be something more efficient, I also have no clue on how to add the spaces other than using shift to the specific places where there has to be an space, because that wouldn't work if the string changes. So i'm really lost.

7. A string that takes a full name and it returns just the first name and the first letter of the surname:

//======================  EXAMPLE  ========================
shortener("Ada lovelace")
"Ada L."// <======  EXPECTED OUTPUT
shortener("Antonello sanna")
"Antonello S." // <======  EXPECTED OUTPUT
//=========================================================


I wrote this but I don't know how to affect just the surname and return the whole first name:

function getInitials(x){
    var seperateWords = x.split(" ");
    var acronym = "";
    for (i = 0; i < seperateWords.length; i++){
        acronym = (acronym + seperateWords[i].substr(0,1));
    }
    document.register.username2.value = toUpperCase(acronym);
}



8. A function that is a japanese budget tracker that returns the average expense per day in dollars being each element of the array in Japanese yens, so it has to convert it to dollars with the conversion rate 0.0089 dollars per yen:

//======================  EXAMPLE  ========================
var expenses = [
        //monday
        '10003', 
        //tuesday
        '46733', 
        //wednesday
        '45833', 
        //thursday
        '3534', 
        //friday
        '57354',
        //satuy
        '45334',
        //sunday
        '34856'     
]


budgetTracker(expenses)
310 // <======  EXPECTED OUTPUT
//=========================================================


I have no clue on how to do it.

And the last one:
9. A function that takes an array and a integer to indicate the minimum length as arguments and returns the last element from the array with length bigger than the minimum length:


//======================  EXAMPLE  ========================

let fruits = ['banana','kiwi','orange','apple','watermelon','pear']
longestString(fruits, 5)
'watermelon' // <======  EXPECTED OUTPUT

//=========================================================

`

I also have no clue on how to do it.

So this are my issues and the things I need to learn, thanks to all of you in advance for the time and help. I'm starting right now with programming but I hope I can contribute here also and help others in the future, because I gotta learn first.

What I have tried:

1.//Solved, I forgot to write the return statement with the right variable in place of document.write. the proper function would be:

function isEven(arr){
    var count = 0;
    for (var i; i < arr.length; i++) {
      if (arr[i]%2 == 0){
            count++
        }
       
    }
    return count;
}



2.// Solved, I had to remove "console" and declare the variable count outside th forEach loop so it keeps the values while looping. Here would be it:
function looper(arr) {
  var count = 0;
  arr.forEach(function(item, index) {
    count++;
    console.log("I am item ", item, "I am the index ", index);
  })
  return count;
}


3.//Solved, again I had to declare the variable outside th forEach loop, and actually declare all variables I use. Here would be the solution:

function isString(arr){
        var arr2 = [];
        arr.forEach(el => {
            if(typeof el === 'string'){
             arr2.push(el);
            }
          });
          return arr2;
        }



4.//Solved again, the variable has to be declared outside the forEach loop, otherwise it just keeps the last loop value:
function timesTwo(array){
    arr2 = [];
    array.forEach(function multiplyByTwo(arrayElement){
        var X = arrayElement * 2;
        arr2.push(X);
    });
    return arr2;
    console.log(arr2);
}


5. I don't know how to start with this, it has to compare two arrays of the same length and return the number of matches,so the functions has to iterate trought the two arrays and check the element and the index, and then if those match add it to a new variable or create a count and increase it, Right? Maybe something like this would work?:
function twoArrays(array1, array2){
    var count = o;
    if (array1[i]=== array2[i]){
        count++;
    }
    return count;
}


6.I know how to put everything in lowercase but I don't know how to remove the numbers other than using .slice() several times with each number, but I believe there has to be something more efficient, I also have no clue on how to add the spaces other than using shift to the specific places where there has to be an space, because that wouldn't work if the string changes. So i'm really lost.

7.I wrote this but I don't know how to affect just the surname and return the whole first name:

function getInitials(x){
    var seperateWords = x.split(" ");
    var acronym = "";
    for (i = 0; i < seperateWords.length; i++){
        acronym = (acronym + seperateWords[i].substr(0,1));
    }
    document.register.username2.value = toUpperCase(acronym);
}
Posted
Updated 17-Aug-21 0:55am
v3

Quote:
But to me it just returns undefined I don't know why.//Solved, I forgot to write the return statement with the right variable in place of document.write. the proper function would be:

Indeed, the return matters, but your function is still wrong, the position of return matters too:
JavaScript
function isEven(arr){
    var count = 0;
    for (var i; i < arr.length; i++) {
      if (arr[i]%2 == 0){
            count++
        }
        return count  // result for first element of array
    }
}

should be replaced with:
JavaScript
function isEven(arr){
    var count = 0;
    for (var i; i < arr.length; i++) {
      if (arr[i]%2 == 0){
            count++
        }
    }
    return count // result for all elements of array
}

For other syntax error, I let you learn JS syntax by yourself.
JavaScript Tutorial[^]
 
Share this answer
 
v2
Comments
gabriel19971029 17-Aug-21 6:56am    
That is right, thanks for the help!
1) Your isEven function writes the count to the document for every iteration of the loop. It doesn't return anything.

2) You've called your callback function console, which hides the built-in console object. Your code also doesn't do what the question asks.

3) You haven't declared the variables i or arr2.

4) You're resetting the arr2 array for every element in the array. That will clear out all previous results. You'd probably have better luck using the map method[^] instead of the forEach method.

5) You haven't shown any code, so we can't tell you what's wrong with it.

6) An extremely poor question. Adds spaces where, precisely?

7) Think about what you're doing. You need to return the whole value for every part of the split name except the last. Modify separateWords[separateWords.length - 1] instead of the entire array, and use the join method[^] to combine the resulting array into a string.

8) You know how to convert each element of the array from question 4. You just need to sum the converted elements, which you can do with the reduce method[^].

9) The question is not entirely clear - what happens if the array is not longer than the minimum length? Otherwise, you simply need to test the array's length and return the specified item if it's long enough.
 
Share this answer
 
Comments
gabriel19971029 17-Aug-21 5:50am    
Thanks a lot Richard! sorry for the poor questions, I just started this week with programming, I'll keep working to improve my coding abilities, and knowing how to perform better questions, and in the future help others as I'm been helped.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900