Home > Blockchain >  checks the data type of array with loop and conditionals
checks the data type of array with loop and conditionals

Time:10-02

i want to check the array for the same datatypes. i found other solutions here but i want to do it with for loop and if conditonals. Can someone please explain, why my code is not working:

thank you very much!

function sameDataType(array){
    const helper = []
    for(let i = 0; i < array.length; i  ){
        let dataType0 = typeof(array[i])
        let dataType1 = typeof(array[i 1])
        if(dataType0 === dataType1){
            helper.push(1)
        } else {
            helper.push("not")
            }    
    }    
    for(let j = 0; j < helper.length; j  ){
        if(helper[j] === helper[j 1]){
            return "same"
        } else {
            return "different"
        }
    }
}
console.log(sameDataType([1, 1, "string"]))

CodePudding user response:

Please use Array.map and Array.filter function.

First you get array of types.

And then filter it with removing the duplicated values.

Then check the length.

Like this.

function sameDataType1(array){
    return array.map(val => typeof val).filter((val, index, self) => self.indexOf(val) === index).length === 1 ? "same" : "different";
}
console.log(sameDataType1([1, 1, "string"]))

CodePudding user response:

Will try to improve upon your code only.

Firstly check if the array even has enough elements. If only one element, simply return same. Then make sure you run your loop till the correct indices. Notice you have i 1 & j 1 in your code. You do arr[arr.length 1], you are getting undefined.

Also check for the condition when you have only two elements.

function sameDataType(array){
if(array.length > 1 ) {
    const helper = []
    for(let i = 0; i < array.length - 1; i  ){
        let dataType0 = typeof(array[i])
        let dataType1 = typeof(array[i 1])
        if(dataType0 === dataType1){
            helper.push(1)
        } else {
            helper.push("not")
            }    
    }    
 
    if(helper.length  === 1 ){
    if(helper[0] === 1) return "same";
    return "different";
    
    }
    for(let j = 0; j < helper.length-1; j  ){
        if(helper[j] === 1 && helper[j] === helper[j 1]){
            return "same"
        } else {
            return "different"
        }
    }
}
return "same";
}
console.log(sameDataType([1, 1 , "string"]))
console.log(sameDataType([1, "string:" ]))
console.log(sameDataType(["string", "string" , "string"]))

  • Related