2

Just started with Javascript and am trying to check the type of an element in an array: I have a function that takes two functions as parameters. I have an array which has a combination of string and number elements. The idea is to trigger functions based on the type of element in the sample array and then push a new element to a new array. I'm not sure which bulit in function i can use here. I tried indexOf and typeof but these don't seem to serve the purpose or maybe I'm doing this wrong. Below is the code. Thanks a lot!

var arr1 = [3, "Hello", 5, "Hola"];

function setNewArray(arr, funct1, funct2){
    var arr2 = [];

    for(var i = 0; i < arr.length; i++){
        if(/*check if arr[i] is a string*/){
            arr2.push(funct1(arr[i]));
        }

        if(/*check if arr[i] is a number*/){
            arr2.push(funct2(arr[i]));
        }       
    }
    return arr2;
}


var numfunct = function(item){
    return item * 2;
}


var strfunct = function(item){
    return item + " " + "there";
}

var result = setNewArray(arr1, numfunct, strfunct);
console.log(result);
2
  • 1
    Yes typeof is what you need, how did you used it? Commented Nov 1, 2017 at 4:52
  • Have a look at the documentation of typeof, parseFloat and parseInt. Commented Nov 1, 2017 at 5:00

8 Answers 8

5

You can do it easily using typeof like following

For the first code block

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

For the second one

if(typeof arr[i] === 'number'){
      arr2.push(
      funct2(arr[i]));
    }   
Sign up to request clarification or add additional context in comments.

2 Comments

@Ben If you think this one solves your problem please mark it as an answer.
Your code does not solve the problem because there is another problem with OP's code, they are passing the function for the number as func1 (same thing for the string function), and this is why I believe your question was not accepted.
1

Create an object of functions, where each function name is the type it can handle. Iterate the array with Array#map, and select the right method from the object using typeof.

Note: I've added a boolean handler to convert the true to yes.

var arr1 = [3, "Hello", 5, "Hola", true];

var fns = {
  number(item) {
      return item * 2;
  },
  
  string(item) {
    return item + " " + "there";
  },
  
  boolean(item) {
    return item ? 'yes' : 'no'
  }
};

function setNewArray(arr, fns) {
  return arr.map(function(item) {
    return fns[typeof item](item);
  });
}

var result = setNewArray(arr1, fns);
console.log(result);

1 Comment

All this is just unnecessary and needlessly smart.
1

Check this:

var arr1 = [3, "Hello", 5, "Hola" ];

function setNewArray(arr, funct1, funct2){

    var arr2 = [];

    for(var i = 0; i < arr.length; i++){

        if(!isNaN(arr[i])){ // or use this alternative typeof arr[i]  == 'number'
         arr2.push(   
            funct1(arr[i]));
        }


        if(typeof (arr[i]) == 'string'){

          arr2.push(

              funct2(arr[i]));
        }       


    }
    return arr2;
    }


var numfunct = function(item){

    return item * 2;

}


var strfunct = function(item){

    return item + " " + "there";
}

var result = setNewArray(arr1, numfunct, strfunct);
console.log(result);

5 Comments

Why not just typeof arr[i] === "number" ? isNaN seems to provide only one advantage in this case, and that in an extremely unlikely case.
@Taurus I edited my answer. I just wanted to use an alternative.
I recommend editing it back then, that alternative was a bit different than the other solutions here, with this edit, your answer looks like a 1-to-1 clone of every other answer to this question.
@Taurus how about both? :-)
Nice but almost invisible :)
0

Try using typeof Operator in javascript

var arr1 = [3, "Hello", 5, "Hola"];

function setNewArray(arr, funct1, funct2) {
    var arr2 = [];
    for (var i = 0; i < arr.length; i++) {
        if (typeof arr[i] == 'string') {
            arr2.push(funct1(arr[i]));
        }
        if (typeof arr[i] == 'number') {
            arr2.push(funct2(arr[i]));
        }
    }
    return arr2;
}


var numfunct = function (item) {
    return item * 2;
}


var strfunct = function (item) {
    return item + " " + "there";
}

var result = setNewArray(arr1, strfunct, numfunct);
console.log(result);

I think this is the exact function that you are looking for.

Comments

0

The problem was not with the use of typeof operator but with the function called with number and string.

Updated code:

var arr1 = [3, "Hello", 5, "Hola" ];

function setNewArray(arr, funct1, funct2){

    var arr2 = [];

    for(var i = 0; i < arr.length; i++){

        if(typeof arr[i] == "string"){
         arr2.push(   
            funct2(arr[i]));
        }


        if(typeof arr[i] == "number"){

          arr2.push(

              funct1(arr[i]));
        }       


    }
    return arr2;
    }


var numfunct = function(item){

    return item * 2;

}


var strfunct = function(item){

    return item + " " + "there";
}

var result = setNewArray(arr1, numfunct, strfunct);
console.log(result);

Comments

0

You can use typeof to check the type of any variable or object. And you do not need to pass the function refrence. Here is the code:

var arr1 = [3, "Hello", 5, "Hola"];

function setNewArray(arr) {
  var arr2 = [];

  for (var i = 0; i < arr.length; i++) {

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

    if (typeof arr[i] === 'number') {
      arr2.push(
        numfunct(arr[i]));
    }
  }
  return arr2;
}

var numfunct = function (item) {
  return item * 2;
}

var strfunct = function (item) {
  return item + " " + "there";
}

var result = setNewArray(arr1);
console.log(result);

Here is the output

1 Comment

Passing the functions as parameters makes the code more flexible.
0

the simple and easy trick to get an array type is the prototype: Object.prototype.isString.call(arr);

var arr = [1,2,3];
console.log(Object.prototype.isString.call(arr));

it will return you [object array]

Comments

0

You can make use of the below which i have refactored the code and that meets your output.

  1. you just need only one funct utility that decides between the type of variable(str)
  2. The isStringPrimitive() utility strongly check if it was created with '' literal(return true) or instead of new String() returns false;
  3. use let instead of var because we are using (...)spread operator below.
  4. use forEach loop makes more meaningful way of coding instead of native for(var i=0; condition; increment/decrement) syntax.
  5. One funct uiltiy is sufficient -> var result = setNewArray(arr1,funct);

var arr1 = [3, "Hello", 5, "Hola"];

// you just need only one funct utility that decides between the type of variable(str)
const funct = function(item){
   return isStringPrimitive(item) ? item.concat(" ", "there") : item *2 ; 
  
} 

// this utility strong check if ut was create with '' literal(return true)  instead of new String() returns false;
const isStringPrimitive = (str) => {
  return typeof str === 'string' && !(str instanceof String);
}

// can utilize this if need 
const isNumberPrimitive = (str) => {
  return typeof str === 'number' && !(str instanceof Number);
}


function setNewArray(arr, funct1, funct2){
    // use let instead of var because we are using spread operator below
    let arr2 = []; 

    // use forEach loop makes more meaningful way of coding instead of native for(var i; ;) syntax
    arr.forEach((value) => {
      isStringPrimitive(value) ? arr2 = [ ...arr2, funct(value)]: arr2 = [ ...arr2, funct(value)];
    });
    
    return arr2;
}

var result = setNewArray(arr1,funct); // one funct uiltiy is sufficient
console.log(result); // [ 6, 'Hello there', 10, 'Hola there' ]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.