Click here to Skip to main content
15,877,051 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have two input fields in JavaScript.

a 'from' text field.

and a 'to' text field.

when a user enter number e.g. 10 in from field and 20 in to field , i want it to be matched against an array which has random numbers. And how many numbers are present in the array from 10 to 20 lets say 4 numbers , I want them to print inside a text field in html file.

i m trying but unable to make this functionality ,

note: i am only using vanilla JavaScript.

What I have tried:

let from1 = document.querySelector(".from");
  let to1 = document.querySelector(".to");


(jsondata[0]["10015022013"].includes(from1.value && to1.value))

  ) 
  
  {
    console.log('hello');
  }
Posted
Updated 10-Jun-21 1:26am

1 solution

includes returns a flag indicating whether the specified value exists in your array:
Array.prototype.includes() - JavaScript | MDN[^]

In this case, you are combining two strings with the && operator. That's not a sensible operation - in my browser, it seems to consistently return the second string, but other browsers might behave differently.

Use parseInt to convert the value to a number:
parseInt() - JavaScript | MDN[^]

Then use filter to filter your array to just the values between those two numbers:
Array.prototype.filter() - JavaScript | MDN[^]

Then do something with that filtered array.
JavaScript
const startValue = parseInt(from1.value);
const endValue = parseInt(to1.value);
const matchingValues = sourceArray.filter(i => startValue <= i && i <= endValue);
console.log("Match:", matchingValues);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900