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

JavaScript's Set data structure does not allow for the storage of strings

As I retrieve a collection of data consisting of questions from mongoDB, I am attempting to place them in a random question set. However, the set is not accepting any input and is returning empty. module.exports.java = async (req, resp) => { // const ...

Retrieving a JSON element using its name within a subquery in a Node.js MySQL environment

I've been working on a project that involves NodeJS and Mysql for the backend. Everything was going smoothly until I encountered a small issue after adding a SUBQUERY. Below is the Mysql Query: var GetHistoryPayments = function(code){ var qu ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

Determine the Mean of Every Set of Values Extracted from a Document

Currently, I have a program that reads data from a text file and displays a list of numbers in a list box. Now, I need to enhance the program to calculate the average of each series of numbers, where each series is separated by a 0. I plan to store the dat ...

Providing dual outputs simultaneously within a function

Is there a way to have a function return two integer values simultaneously in the C programming language, or is it better to create separate functions for each value? ...

Tips for verifying conditional input fields in a React component?

As a beginner in React, I attempted to create a SignIn form component that dynamically changes its layout based on a boolean prop toggled between Login and Signup options. In the signup version, there is an additional text field labeled Confirm password, w ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

PugJS is failing to properly interpolate numbers from the JSON file

My goal is to display a list of interfaces retrieved from my router API, which is in JSON format. However, when using Pug, only the strings are being rendered and not the numbers. Here is the output (it displays correctly in HTML): em1 192.168.0.0/24 Addr ...

To clear the previous result of an AJAX call in JavaScript, reset the function or variable

I encountered a problem previously, and now another issue has come up. It appears that the previous result from my ajax JavaScript is still being displayed, and I need to prevent that from happening. I've tried deleting the variable, setting it to und ...

Looking to add a close button to the iFrame, but having trouble getting it to function when clicked

In my project built with Meteor, I have integrated an iframe to display specific content to the user. The iframe is functioning as expected, but I am looking to add a close button that will effectively unload the iframe when clicked. I attempted to imple ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...

The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task: This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array. The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characte ...

Unable to retrieve information from the firestore database

When trying to fetch documents from the firestore, I encountered an issue where it returns an empty array. However, when I run console.log(docs); outside of the declared function, it actually shows the array data. This problem arises because my useEffect f ...

Leveraging the flexibility of an undefined variable as a useEffect dependency

Summary: Need help using listRef.current.clientWidth as a dependency in useEffect. I'm working on creating a dynamic list that automatically adjusts the width of its items based on the list's width. I've almost got it working, but I'm ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

What is the best way to remove an object from an array in MongoDB?

I am currently using MongoDB and Node.js, but I am facing a small issue when trying to delete an object from an array of objects. Below is the code snippet causing the problem: router.route('/deleteGuestFromJam/:id').delete(function(req, res){ ...

Issue with alert dismissal button not visible

I am dynamically updating the alert message: <div id="alert" hidden="hidden"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> </div> $('#alert').addClass("alert alert-dan ...

TinyMCE: Tips for adding and highlighting text in your content!

Is there a way to insert, or even replace the current selection with some content and then have it automatically selected? Take for instance this text: Hello nice world! The user has selected nice. After clicking a button, this code is executed: editor. ...

Analyzing the DOM content loading time for web pages generated using AJAX technology

When analyzing website performance, I rely on window.performance.timing. However, this method falls short when it comes to measuring the performance of webpages loaded through ajax calls. For instance, websites built with frameworks like angularjs often lo ...