0

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"]))
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39

2 Answers2

0

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"]))
Kirill Savik
  • 1,228
  • 4
  • 7
0

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"]))
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • thank you very much! but why did you use < array.length -1 ? I think it should be <= array.length -1 – sugar42 Oct 01 '21 at 11:05
  • If `i = array.length - 1`, `i+1 = array.length`. So for an array of length 3 you cannot do array[3] right, that is `undefined`. And comparing your element with undefined is false only right. Why do it – Tushar Shahi Oct 01 '21 at 11:11