I want to obtain an array from a user input using a prompt and then use that array to filter() and get a specific array.
I have used the following:
var number = prompt("write your number","");
var matrix = number.split("");
and I get the desired array but when I applied the filter() method to the matrix array it does not seem to work. I would like to get an array with just the numbers 3s.
The code that I present here works because I have defined the array in the code itself. But I want to use a user input instead.
<script>
var matrix = [3,2,2,3,2,3];
function find_3(value) {
return (value === 3);
}
var result = matrix.filter(find_3);
document.write(result);
</script>
4
Answers
Maybe in your case could be sufficient to use simple equality
==
:Reason:
prompt()
returns a string instead of a number.Otherwise you would need to parse user input:
After getting the input (as a
string
) and splitting it into astring[]
, you will need to map the values to aNumber[]
by callingparseInt
.Remember that the values obtained from a prompt is a string, so, basically, you are not getting
But getting:
To fix this, you can transform those strings into numbers: