Filter an array based on the number of characters in each element using user-entered measurements

I am a very novice programmer and a little fixated on practice.

I want to learn how to filter elements in an array based on the number of characters in each element (my array is a list of 30 states). Basically, the user enters sizes (the number 0-40, as well as the minimum and maximum) in two text fields and presses the enter button, then the array should be changed based on these numbers (deleting elements that do not meet the entered specifications),

I have HTML installed without any problems, but I'm completely stuck on Javascript. I tried to use a “filter”, but it doesn’t seem to do what I want.

Any help would be appreciated!

+4
source share
2 answers

You can use the function Array.prototype.filter. It accepts one custom function, which should return trueor false. For example, this code takes an array ints, creates a new array using a user-defined function (removes even numbers) and assigns it back ints:

var ints = [1, 2, 3, 4, 5];
ints = ints.filter(function(x) { return x % 2 === 1; }); // ints is [1, 3, 5] now

What you can use in your case:

// When a user clicks a button
document.getElementById('calc').onclick = function() {
  var strings = ['a', 'on', 'the', 'form', 'index', 'length', 'factory'];
  
  // Read values from <input>s
  var minLength = parseInt(document.getElementById('minLength').value);
  var maxLength = parseInt(document.getElementById('maxLength').value);

  // Filter strings array according to the rule (length is between minLength and maxLength)
  strings = strings.filter(function(x) {
    return x.length >= minLength && x.length <= maxLength;
  });

  // Output
  document.getElementById('result').innerHTML = strings.join('<br/>');
};
Min length: <input type="text" id="minLength" value="0"/><br/>
Max length: <input type="text" id="maxLength" value="7"/><br/>

<button id='calc'>Show</button>

<div id="result"></div>
Run codeHide result
+1
source

Let s say your array is defined and called myArray.

I assume that you can take values ​​from the user this way. So I accidentally chose min and max, as shown below.

var max = 40 , 
    min = 0 ; 

for(var i = 0; i < myArray.length ; i++){
 var filteredArray = [];

 if( myArray[i].length >= min && myArray[i].length <= max ){

   filteredArray.push(myArray[i]);

 }

}
0
source

Source: https://habr.com/ru/post/1618840/


All Articles