Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning a "typeof" value in a function?

I’m a total beginner, so it would be very helpful if someone posted the full solution in the comments.

I’m trying to solve the following challenge on edabit:

Create a function that takes an array and returns the types of values (data types) in a new array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

arrayValuesTypes([1, 2, "null", []])
// expected output ➞ ["number", "number", "string", "object"]

arrayValuesTypes(["214", true, false, 2, 2.15, [], null])
// expected output ➞ ["string", "boolean", "boolean", "number", "number", "object", "object"]

arrayValuesTypes([21.1, "float", "array", ["I am array"], null, true, 214])
// expected output ➞ ["number", "string", "string", "object", "object", "boolean", "number"]

So far I have this:

    arr = [1, 2, "null", []]
    
    function arrayValuesTypes(arr) {
        for (let i = 0; i < arr.length; i++) {
         return typeof arr[i]
      }
    }

// output ➞
// 'number'

But when I change "return" to a console.log, it gives me a result closer to what I am looking for. Why is that?

arr = [1, 2, "null", []]

function arrayValuesTypes(arr) {
    for (let i = 0; i < arr.length; i++) {
     console.log(typeof arr[i])
  }
}
// output ➞
// 'number'
// 'number'
// 'string'
// 'object'

>Solution :

Why is that?

Because return inside a function will return the value and so stop the function, regardless of the for loop.


So use map() to apply it for each item in the array, and then return that array created by map:

function arrayValuesTypes(arr) {
    return arr.map(tmp => typeof tmp);
}

const tests = [
  [1, 2, "null", []],
  ["214", true, false, 2, 2.15, [], null],
  [21.1, "float", "array", ["I am array"], null, true, 214]
];
for (let testIndex in tests) {
  console.log(arrayValuesTypes(tests[testIndex]));
}
["number", "number", "string", "object"] 
["string", "boolean", "boolean", "number", "number", "object", "object"] 
["number", "string", "string", "object", "object", "boolean", "number"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading