verify prime numbers in a multidimensional array

I have been searching, but I couldn't find any information on what I am about to ask. As a beginner and student learning JavaScript, I have a question. I am familiar with how to check if a number is prime or not. Here is my current challenge:

numbers([
  [5, 7, 10],
  [8, 2, 3],
  [44, 50, 22]
])

expected output:
[
  ['#', '#', 10],
  [8, '#', '#'],
  [44, 50, 22]
]

What I need is this: if there is a prime number in a multidimensional array, it should be replaced with #, otherwise leave it unchanged. The task specifically prohibits the use of built-in functions such as .indexOf, .include, .findIndex, .reduce, .map, .filter, adding new parameters, or regex. So far, here's what I've attempted:

function multidimensionalPrimesChecker(numbers)
{
    for (var i = 0 ; i < numbers.length ; i++)
    {
        for (var j = 0 ; j < numbers[i].length ; j++)
        {
            if (numbers[i][j] % i === 0)
            {
                return false;
            }
        }
    }
}

I am currently stuck and unsure how to proceed with this problem. Any help would be greatly appreciated. Thank you for your kindness.

Answer №1

To begin with, it is essential to have a function that can determine whether a number is prime or not. Your current check numbers[i][j] % i === 0 only verifies if numbers[i][j] is divisible by i. The following function can be used for this purpose:

function isPrime(num)
{
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false;

    return num !== 1 && num !== 0;
}

Now, incorporating your code, you can detect this condition and replace it with # when the condition is met.

const input = [
    [5, 7, 10],
    [8, 2, 3],
    [44, 50, 22]
];

function isPrime(num)
{
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false;

    return num !== 1 && num !== 0;
}

function multidimensionalPrimesChecker(numbers)
{
    for (var i = 0; i < numbers.length; i++)
    {
        for (var j = 0; j < numbers[i].length; j++)
        {
            if (isPrime(numbers[i][j]))
                numbers[i][j] = "#";
        }
    }

    return numbers;
}

let res = multidimensionalPrimesChecker(input);
console.log(JSON.stringify(res));

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

Combining runs from "on edit" or "on change" triggers in Google Apps Script

I've been working on a script to alert me about low stock items in my inventory tracking spreadsheet, but the script works a little too well. The issue is that each time I update the inventory for 10 items, the script runs and sends out 10 email noti ...

Creating a jQuery alert similar to Stack Overflow's and integrating it with server-side functionality

I recently asked a question but unfortunately couldn't find the answer I was looking for. I came across this discussion on Stack Overflow about creating an alert box with dynamic data, but it wasn't exactly what I needed. After searching online ...

How can NgRx be used to properly reset or empty an array within the state object?

What is the proper way to reset an array in an NgRx reducer? I am using NgRx to create a basic reducer that includes an empty array called myArray in the initial state: import * as MyActions from './my.actions'; const myState = { myValue: & ...

The Ajax request appears to be triggered twice, yet all other associated JavaScript functions are executed only once

Using ajax, I have a code that retrieves the contents of a PHP page every X seconds until completed=="yes". Each time it fetches the content, it displays an alert with <script>alert("checked");</script>. Within the PHP page, there is another al ...

Utilize React's Context Provider to centrally manage all state while incorporating async calls

I am currently exploring more refined methods to establish a provider/consumer setup in which an asynchronous call is initiated from the provider, but the consumer does not need to handle state management. Within my context provider, I am fetching data to ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

Retrieve the value of a JavaScript variable within an HTML or EJS document

My JavaScript file, named main.js, contains a JSON object like the following: const person = {}; person.AGE = '17'; person.GENDER = 'Male'; To load this file in my .ejs file, I use the following code: <script type="text/javascript ...

What is the process for storing strings in an array in the programming language C?

My attempt to collect string inputs from the user and save them in an array ended in disaster as soon as I executed the code. #include <stdio.h> int main() { int i; char *word[3]; for(i=0;i<3;i++) { printf(" Enter a word ...

"Revitalize your React JS project with a rerender

Trying to refresh a list with filtered values... Already displayed all values but now want to show them again with a dropdown menu. Data is sourced locally from a JSON file. [ { "brand": "Toyota", "model": "Corona", "cylinders": 4, "horsepower": 96, "orig ...

Conceal div element when clicked on the client side

Attempting to make this particular div disappear, but it is not behaving as I anticipated. Can someone point out where my mistake lies? The div is not disappearing. JavaScript: <script type="text/javascript> function Show_Hide_Display() { va ...

Guide to adding up the radio button values with Javascript

The tutorials I have reviewed include: How might I calculate the sum of radio button values using jQuery? How to find a total sum of radio button values using jQuery/JavaScript? How might I calculate the sum of radio button values using jQuery? Unfortu ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

The loop is not fully completing all actions during the first iteration

While working on a multiple upload feature using the Multiple_upload library in CodeIgniter, I encountered an issue where the loop that generates thumbnails only runs on the first iteration. Here is the relevant code snippet: function saveContentImages() ...

Combining Various Input Types for Seamless Integration: Getting Files and Text to Collaborate Efficiently

In my form, I have two types of image inputs - one from a file and the other from a URL. To ensure that the image from the last changed input is used, I created an additional invisible input field called "imgTempURL". This field is filled with the image&ap ...

What could be causing my function to fail to return the array?

Here is the code snippet I am working with: document.getElementById('revealUser').onclick = displayDaUsers function displayDaUsers(){ pullAllUsersFromDB(); debugger; } function pullAllUsersFromDB(){ rootRef.child('users').on(& ...

capturing the value of a button during the onChange event

I'm currently trying to retrieve the button value within an onChange event. My goal is to then bind this value to state, but unfortunately, I am receiving an empty value. <button onChange={this.handleCategoryName} onClick={this.goToNextPage}> ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Error: The filter argument must be in object form

Currently I am in the process of developing a REST API with an endpoint for posting movies. The request body is expected to contain only the movie title, which needs to be validated for presence. Upon receiving the title, I need to fetch other movie detail ...

Is it the right time to implement a JavaScript framework?

Is there a need for using JavaScript frameworks like Angular or React if you are not developing single-page websites or components that receive live updates? ...

Is it possible to invoke a helper function in Node.js from within a callback?

I recently started programming with node.js and I am encountering an error that I can't quite figure out. The function appears to be correctly set up, and I don't believe there are any asynchronous issues because of the self variable I have in pl ...