Using iteration and conditional statements to verify the data type of an array

I'm attempting to check the array for the same data types using a for loop and if conditionals. However, my code doesn't seem to be working as expected. Can someone please help me figure out why?

Thank you in advance!

function checkDataTypes(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(checkDataTypes([1, 1, "string"]))

Answer №1

Utilize both Array.map and Array.filter methods to accomplish the task.

Start by creating an array of data types from the input.

Next, filter out any duplicate values within the array.

Finally, check the length of the filtered array to determine if all elements are of the same type.

Here's an example implementation:

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

Answer №2

Attempting to enhance your code.

Before proceeding, ensure that the array contains an adequate number of elements. In cases where there is only one element, the function should simply return same. Moreover, it is important to correctly define the loop boundaries. A specific attention should be paid to the references i+1 and j+1. It seems that you are trying to access arr[arr.length+1], which will result in obtaining undefined.

Another check to consider is when the array consists of exactly two elements.

function evaluateDataTypes(array){
if(array.length > 1 ) {
    const helper = []
    for(let i = 0; i < array.length - 1; i++){
        let type1 = typeof(array[i])
        let type2 = typeof(array[i+1])
        if(type1 === type2){
            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(evaluateDataTypes([1, 1 , "string"]))
console.log(evaluateDataTypes([1, "string:" ]))
console.log(evaluateDataTypes(["string", "string" , "string"]))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS Form Not Resetting After Submission

Currently, I am utilizing AngularJS on the frontend and the Play framework on the backend to handle incoming data. A persistent issue that I am encountering is that the form does not reset itself after successfully submitting the data upon clicking the su ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Failure to pass parameters between different states

There is a situation where clicking on a link should change the route and send some parameters to another state. The problem arises when the parameters appear to be empty when logged in the other state. <div ng-repeat="items in vm.Items"> <a ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

JavaFX: We are experiencing issues with our JavaScript file when we compile the HTML and add the link to the header. What could be causing this problem?

There is a need for the user to be able to change the value, and as a result, the numbers should automatically update. I am facing this issue where the values are not changing correctly. Additionally, I was wondering if it is feasible to link a JS file in ...

Preventing an event from bubbling up to its parent in a jQuery Ajax call: A step-by-step guide

I am working on a page that showcases a tree list using unordered lists. Each li element with children triggers an ajax call to fetch those children and display them as another ul/li combination, which is functioning correctly. However, the problem arise ...

Using JavaScript, locate the previous and next elements in the JSON array of objects based on the given current event ID

Task: To retrieve and display data based on the current event ID from a JSON file: var _getEventById = function(eventId) { var __findEvent = function(event) { return event.id === eventId; }; return _.find(data.meeting ...

Tips for stopping the current webpage from redirecting to a different page upon refreshing

How do I prevent the Profile page from redirecting to the Homepage every time it is reloaded? After a user logs in, they are directed to the Homepage. On the Homepage, there is a link to the Profile Page. The issue arises when reloading the Profile page, ...

Encountering an Issue with Missing Registration Error When Making HTTPPost Requests to GCM in Google Apps Script

I am attempting to send an HTTP POST request to the GCM server using Google Apps Script. I have both the device ID and the necessary credentials. Below is the code I am currently using: function doThat(){ var url = "https://android.googleapis.com/gcm/se ...

JS Difficulty with Applying Underline in Contenteditable

Recently, I encountered a glitch with document.execCommand that seems puzzling. Allow me to explain the situation at hand. $("#underline-btn").click(function() { document.execCommand("underline"); }); <script src="https://ajax.googleapis.com/ajax/l ...

When a POST request fails, which AJAX event is triggered?

How can you handle a failed post request in jQuery AJAX? Suppose the site shows this message: POST http://s-t-h-c.appspot.com/dispatch 500 (Internal Server Error) which AJAX event should you use to address it? In case of a successful request, we typicall ...

Removing fragment identifier from the URL

If you go to stackoverflow.com/#_=_, the expression window.location.hash will display #_=_. All good so far. But when you run window.location.hash = '' to get rid of the hash, the URL changes to stackoverflow.com/#. (Note the unexpected # at the ...

How to choose an item from a dropdown list using its item number with jQuery

Is there a way to select an item in a dropdown menu by its item number using jQuery? <select id="selectbox" style="width: 220px;"> <option value="Option 1">Option 1</option> <option value="Option 2">Option 2</option> < ...

Utilize frontend React.js to directly access a remote API without the need for any server-side coding

Looking to access a remote URL using fetch/axios post API in react.js. Take a look at my react code below- const requestOptions = { method: 'POST', crossDomain: true, mode: 'cors', // no-cors, *cors, same-orig ...

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

Loop through each JSON object and insert it into an HTML element

I am working on looping through a JSON object and converting it into HTML. While I can iterate through all the objects in the JSON, I am having trouble extracting just the first object. var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback ...

Combining and Reorganizing JSON Data with Arrays of Objects

Seeking assistance after spending a considerable amount of time on this task. Our objective is to dynamically merge two JSON responses by utilizing the data from JSON Data 2 (prodsub_id) with JSON Data 1 (id). Refer to the sample JSON data below. JSON Dat ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...