How to count strings and integers from an array of strings in Node.js

1 Answer

0 votes
function isNumeric(str) {
    if (typeof str != "string") {
        return false // not a string
    }
  
    return !isNaN(str) && !isNaN(parseFloat(str)) 
}

const arr = ["2", "99", "java", "34", "c++", "python", "c", "890", "c#", "node.js", "go"];

let totalstrings = 0, totalintegers = 0;

for (const item of arr) {
    if (isNumeric(item)) {
        totalintegers++;
    }
    if (typeof item == "string" && !isNumeric(item)) {
        totalstrings++;
    }
}

console.log(totalintegers);
console.log(totalstrings);

 
 
 
/*
run:
 
4
7

*/

 



answered Feb 18, 2024 by avibootz
...