The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to work through a particular function written in Javascript, I realized that I'm facing challenges as the output is only an empty array []. Here's the problem statement, code snippet, and the actual output:

Challenging Problem Statement

The task is to create a method that takes an integer array as input and processes each number accordingly. The function should return a new array based on specific rules: If the number has a perfect square root, use that value; otherwise, square the number. For example, given [4,3,9,7,2,1], the expected output is [2,9,3,49,4,1]

The Troubling CODE

function squareOrSquareRoot(array) {

    var newValues = []; 
    
    for (i = 0; i < array.length; i++){ 
        
        var initial = array[i]; 
        var sqrt = Math.sqrt(initial); 

        if (Number.isInteger(sqrt)){ 
            newValues.push[sqrt];
        } 
        else { 
            newValues.push[initial*initial];  
        }
    }
    return newArray; 
}

Puzzling OUTPUT

Expected Output: '[2, 9, 3, 49, 4, 1]', Actual Output: '[]'

Expected Output: '[10, 10201, 25, 25, 1, 1]', Actual Output: '[]'

Expected Output: '[1, 4, 9, 2, 25, 36]', Actual Output: '[]'

Answer №1

Your current situation has a flaw. Please adjust the code below:

Number.isInteger(sqrt) == 'true'

to

Number.isInteger(sqrt) == true

The function Number.isInteger returns a boolean value, not a string. Additionally, the second 'else if' statement is unnecessary. If isInteger returns false, simply execute the 'else' part instead of rechecking. Lastly, make sure to return newValues instead of newArray. I hope this explanation clarifies things for you.

Answer №2

There are certain errors in your current approach.

  1. Your function should return newValues instead of newArray.
  2. Avoid using quotation marks for true or false.
  3. Using if/else if for true/false is unnecessary. Use if/else instead.

Below is a corrected solution:

function squareOrSquareRoot(array) {

    var newValues = []; 
    for(var i = 0 ; i<array.length ;i++) {
        Number.isInteger(Math.sqrt(array[i]))?newValues.push(Math.sqrt(array[i])):newValues.push(array[i]*array[i]);
    }
    return newValues;
}

var a = [3,4,5,9,7,16,36,11];
console.log('Input : ' + a);
console.log('Output: ' + squareOrSquareRoot(a));

Input : [3,4,5,9,7,16,36,11]

Output: [9,2,25,3,49,4,6,121]

If you find the ternary expression confusing, here is an example with if/else statement:

function squareOrSquareRoot(array) {

    var newValues = []; 
    for(var i = 0 ; i<array.length ;i++) {
        var initial = array[i];
        var sqrt = Math.sqrt(initial);
        if(Number.isInteger(sqrt)) 
            newValues.push(sqrt);
        else
            newValues.push(array[i]*array[i]);
    }
    return newValues;
}

var a = [3,4,5,9,7,16,36,11];
console.log('Input : ' + a);
console.log('Output: ' + squareOrSquareRoot(a));

Answer №3

A more efficient approach would be to avoid using a for loop and instead utilize the array.map method.

function calculateSquareOrSquareRoot(array) {
  return array.map(function(number) {
    var squareRoot = Math.sqrt(number);
    return Number.isInteger(squareRoot) ? squareRoot : number * number;
  })
}

The Array.map function iterates over each item in the array, applies the specified function, and returns a new array with the results.

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

Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement) Upon sending data to the server as shown below, the body appears empty. Server // Route for POST method app.post('/pass', function (req, res) { ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Error encountered in the main thread: Fail to click on element at current position

An error occurred in thread "main" org.openqa.selenium.WebDriverException: The element located at point (126, 7.98333740234375) is not clickable. Another element is intercepting the click: <div class="_1H5F__" data-reactid="10"></div> The com ...

Create a custom countdown using Jquery and Javascript that integrates with MySQL and PHP to display the datetime in the format Y-m-d

Hey there, I'm looking to create a countdown script using dates in the format (Y-m-d H:m:s). The goal is to retrieve the current_datetime and expire_datetime in this format and incorporate them into some JavaScript or jQuery plugin to display a countd ...

Steps for adding a class to an element in VueJS

https://codepen.io/nuzze/pen/yLBqKMY Here's my issue at hand: I currently have the following list stored in my Vue data: { name: 'Camp Nou', id: 'campNou' }, { name: 'Abran cancha', id: 'abranCancha ...

JavaScript Issue Causing Jquery Carousel Dysfunction

I am having trouble with the slider I created using JS Fiddle. The link to the slider is not working and I need some assistance. Click here for the slider <div class="row"> <div id="myCarousel" class="carousel slide vertical"> &l ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

Using numpy's vectorize function with a 2-dimensional array

I have a numpy array with dimensions of (m, 2) and I am looking to reshape it into (m, 1) using the function provided below. def customFunction(x): if x == [1., 1.]: return 0. if x == [-1., 1.] or x == [-1., -1.]: return 1. if x ...

Why is it necessary to use process.nextTick() to delay method execution within a PassportJs strategy using Express?

When working with user registration using the passport local strategy, I stumbled upon a code snippet that utilizes process.nextTick to postpone the execution of a method within the Passport LocalStrategy callback. While I grasp the concept of delaying m ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...

Is innerHTML incapable of executing JavaScript code?

Experimenting with a new technique where I divide my code into separate files to create multiple HTML pages instead of one large one. Using ajax to load them and then setting the content as innerHTML to a parent div results in clean code that works well in ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

Unable to showcase information in a jQuery UI popup through AJAX when initially presented

I'm trying to display reviews from my database on a jQuery UI dialog box upon loading, but nothing is showing up. Here are the reviews: {"results":[{"review_text":"good"},{"review_text":"not bad"},{"review_text":"great"}]} Can someone please check m ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

What is the method to retrieve the value from $.get()?

After searching on stackoverflow, I was unable to locate a solution to my issue and am currently unable to comment for further assistance. The dilemma I face involves extracting a return value from an asynchronous method to pass it onto another function: ...