+ 1
Please help with simple JS code that returns a prime numbers from given array
My code doesn't work properly. I have a solution, but it's have to be a function. Here is what I got so far: function numArray() { numArray.filter((number) => { for (var i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) return false; } return true; }); numArray([1, 2, 3, 5, 7, 10, 12, 13, 15, 20]); Thanks!
11 Respuestas
+ 3
or:
myArray = [1, 2, 3, 5, 7, 10, 12, 13, 15, 2];
function prime(arr){
return "The prime numbers are: " + arr.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
}
alert(prime(myArray));
+ 4
function numArray(numArray) {
var result = numArray.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
return result;
}
alert(''+numArray([1, 2, 3, 5, 7, 10, 12, 13, 15, 20]));
+ 4
Your mistakes:
> you haven't closed the { of the numArray() function
> you doesn't have declared the parameter of the function
> you doesn't return the result from the function
> and finally, you call the function, without storing (or outputing in my fix) the returned value
+ 4
@Ulisses Cruz: You're right (edited my solution)... I usually test more, but actually my internet connexion is lagging so much, and I read the result too fast :P
@DIY mods:
one mistake more:
> you don't store the result of the filter() method ;P (thanks to @Ulisses Cruz ^^)
+ 3
You use array functions, and advanced method as filter(), but you don't know how to format a string? @@
alert("The prime numbers are: "+JSON.stringify(prime(myArray)));
... or just:
alert("The prime numbers are: ["+prime(myArray)+"]");
+ 2
Detailed tuto for prime number implementation in this code:
https://code.sololearn.com/WPXD8LSoeiIL/?ref=app
(second part with implementation of GCD calcul is also available in my codes ;))
+ 2
do:
alert("The prime numbers are: " + prime(myArray));
+ 1
Thank you for the answer! I understanding the logic, and I have a working code, that I have to turn into the function. Here it is:
var numArray = [2, 3, 4, 5, 6, 7, 8, 9, 10]
numArray = numArray.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
console.log(numArray);
+ 1
@visph you have to start to test you codesbefore you post them.
In this case it will not work correctlly because the filter method will not affect the array, just return another affected array.
0
This code works, thanks to Ulisses Cruz!
myArray = [1, 2, 3, 5, 7, 10, 12, 13, 15, 2];
function prime(arr){
return arr.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
}
prime(myArray);
However, how to add a string to make it looks like 'The prime numbers are: [x,x,x,x,x]'