Searching for the prime numbers within an array and then saving them into a separate array using Javascript

I have been working on a program that aims to identify prime numbers within an array and store them separately. While the code seems to be functioning correctly overall, there is an issue where a non-prime number (33) is incorrectly labeled as prime due to it being divisible by 3 and 11. I suspect there may be a small error in my code causing this issue. Any guidance or assistance would be greatly appreciated. Thank you!

var array = [33,23,5,7,10,20,30,12,37];
primes(array);



function primes(arr){
    var arrayLength = arr.length;
    var primeArray = [];

    function primeNum(arrElement){
        if (arrElement <= 1){
            console.log(arrElement + " is not a valid test number.");
        }
        for (var x = 2; x < arrElement; x++){
            if (arrElement % x === 0){
                return false;
            }
            return true;
        }
    
    }

    for (var y = 0; y <= arrayLength - 1; y++){
        if(primeNum(arr[y])){
            primeArray.push(arr[y]);
        }
    }
    console.log(primeArray);
    }

Here is the resulting output: (5) [33, 23, 5, 7, 37]

Answer №1

def find_primes(arr):
    primes_list = []
    
    for num in arr:
        if is_prime(num):
            primes_list.append(num)
    
    return primes_list
            
def is_prime(n):
    if n <= 1:
        print(str(n) + " is not a valid test number.")
        
    for x in range(2, n):
        if n % x == 0:
            return False
    
    return True

numbers = [7, 13, 24, 31, 37, 40, 47]
print(find_primes(numbers))

The return true statement in the is_prime function should be placed outside the for loop.

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

Troubleshooting the issue of not successfully retrieving and sending values from form checkboxes in jQuery to $_POST variable

I am facing an issue with checkboxes that have identical names and use square brackets to create an array. <label> <input type="checkbox" value="Tlocrt objekta" name="dokument[]" > Tlocrt objekta </input> </label> ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

Having trouble making the JavaScript mouseenter function work properly?

Hi there, I'm having trouble with this code and I can't figure out why it's not working. $('#thumbs > li').mouseenter(function() { $(this).find("div").fadeIn(); }).mouseleave(function(){ $(this).find("div").fadeOut(); ...

How can the actual values from the Repeater be retrieved using Protractor, instead of the Elements?

As I develop a Protractor script to test my quiz game, which involves displaying random questions and answers, I am faced with the challenge of identifying the correct answer. This information is not directly available as an element on the page, so I need ...

What could be causing the divs to overlap? Without the use of floats or absolute positioning,

When resizing vertically on mobile, my date-time-container is overlapping the upper elements welcome and weather. Despite setting them as block level elements, adding clear: both, and not using absolute positioning or floats, the overlap issue persists. An ...

Troubles with creating promises in Node.js

Currently, I am facing a challenge in Nodejs where I need to execute asynchronous tasks. Specifically, I need to navigate through all levels of a JSON object sequentially but synchronously. I am experimenting with the following code snippet, which is a si ...

Error encountered when attempting to embed a SoundCloud player in Angular 4: Unable to execute 'createPattern' on 'CanvasRenderingContext2D' due to the canvas width being 0

I attempted to integrate the SoundCloud iframe into my Angular 4 component, but encountered the following error message: Failed to execute 'createPattern' on 'CanvasRenderingContext2D': The canvas width is 0. Here is the iframe code ...

Managing ajax requests for lazy loading while scrolling through the middle of the window can be a challenging task. Here are some tips on

I have implemented Lazy loading in my Project. I found a reference at which explains how to make an ajax call after scrolling and image upload with slow mode without allowing scrolling until the loader is shown. The code snippet I am using is as follows: ...

AngularJS is throwing an error because the current.$$route object is not defined

Having worked with AngularJS, I encountered an error when trying to set a title. Here is my App.js 'use strict'; var serviceBase = 'http://www.yiiangular.dev/' var spaApp = angular.module('spaApp', [ 'ngRoute' ...

Utilize Express Handlebars to render an input-generated list for display

My goal is to showcase a collection of wishlist items on a basic webpage through user interaction. Here's how I envision it: 1. do something 2. do another thing 3. blahblah This snippet shows my index.js code: var wishlist = []; router.post('/& ...

How can I briefly alter the background color of a view in React Native for just 1 second each time the state is modified?

Is it possible to briefly change the background color of a view and then revert back to its original color whenever the state changes in React Native? How can this challenge be tackled? Is it necessary to monitor the previous state, compare it, and imple ...

Using ReactJS to trigger an onClick event on a specific element within an array

I am looking to enhance the image grid selection functionality. Currently, I can only choose one image at a time which automatically deselects others. My goal is to be able to select multiple images simultaneously. Unfortunately, I am unable to implement ...

Can you provide guidance on transforming a JSON date format like '/Date(1388412591038)/' into a standard date format such as '12-30-2013'?

I have a json that is created on the client side and then sent to the server. However, I am facing an issue with the conversion of the StartDate and EndDate values. Can someone please assist me with this? [ { "GoalTitle": "Achievement Goal", ...

Tips for updating values in a nested array within JSON

I am working with the following .json file and my goal is to update the values of "down" and "up" based on user input. "android": { "appium:autoAcceptAlerts": true, "appium:automationName": "UiAutomator2", ...

Is there a way to display all articles within an array while utilizing a computed property to sort through outcomes on VueJS?

I am currently utilizing VueJS to display a collection of articles. Additionally, I have integrated filters that utilize checkboxes and a computed property to refine the display of articles based on the selected tag. However, I am interested in incorporat ...

Karma, Webpack, and AngularJS are successfully passing all tests, yet encountering karma errors with an exit code of 1

Currently running karma 4.0.1, webpack 4.31.0, angular 1.6.8, karma-jasmine 2.0.1, jasmine-core 3.4.0 Recently at my workplace, I transitioned our angularjs application from a traditional gulp build process to webpack + es6. The journey has been smooth wi ...

utilize dynamic variables in post-css with javascript

Question: Is it possible to dynamically set or change variables from JavaScript in post-css? I have a react component with CSS3 animations, and I want to set dynamic delays for each animation individually within each component. I've found a similar s ...

Loop Swig with Node.js and Express!

I'm attempting to create a loop in order to access array objects using swig. The goal is to make a loop that checks the object's length. I am able to access the objects by {{styles[0].style}}, where [] represents an array. So, essentially what I ...

Retrieving values from input fields in a table using JQuery and storing them in an array

I am working with a table that contains input fields within each td element. My goal is to use JQuery to retrieve the values from the input fields upon button click and store them into an array, representing one row at a time. Since each row has different ...

Exploring the process of implementing inheritance in TypeScript from a JavaScript class

I am using a JavaScript module to extend a Class for a Custom extended Class. I have written my Custom Class in TypeScript, but I encountered the following error messages: Property 'jsFunc' does not exist on type 'tsClass'.ts(2339) I ...