skip to Main Content

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


  1. Maybe in your case could be sufficient to use simple equality ==:

    function find_3(value) {            
      return (value == 3);
    }
    

    Reason: prompt() returns a string instead of a number.

    Otherwise you would need to parse user input:

    function find_3(value) {           
      return (Number.parseInt(value) === 3);
    }
    
    Login or Signup to reply.
  2. const X = 3;
    const result = []
    const totalElements = prompt("Enter total no of elements: ");
    
    
    for (let counter = 1; counter <= totalElements; counter++) {
      const n = Number(prompt(`Enter element no ${counter} :`))
      if (n === X) {
        result.push(n);
      }
    }
    
    console.log('Result : ', result);
    Login or Signup to reply.
  3. After getting the input (as a string) and splitting it into a string[], you will need to map the values to a Number[] by calling parseInt.

    const
      number = prompt("Enter a sequence digits", ""), // 322323
      vector = number.split("").map(n => parseInt(n, 10)), // [3,2,2,3,2,3]
      result = vector.filter(find_3); // [3, 3, 3]
    
    document.write(result); // 3,3,3
    
    function find_3(value) {  
      return value === 3;
    }
    Login or Signup to reply.
  4. Remember that the values obtained from a prompt is a string, so, basically, you are not getting

    [1,2,3,4]
    

    But getting:

    ['1','2','3','4']
    

    To fix this, you can transform those strings into numbers:

    const matrix = number.split("").map(Number);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search