Compare user input with csv file, return second column value javascript

Viewed 59

I came across the following topic, it just has 1 line instead of 2 columns. How do I return the second value here (see topic below) Compare my variable with a csv file and get the matching value in javascript

This is my CSV file values:

csv screenshot of columns

1

This is what I have currently IT just checks the file for the serial number from the user and marks the div with text "Valid". This Valid should have the second Columns value.

<script>
    const checkm = document.getElementById('check');
    checkm.addEventListener('click', serialChecker)
    async function serialChecker(){
        const url = 'http://localhost/validator/serials.csv';
        const response = await fetch(url);
        // wait for the request to be completed
        const serialdata = await response.text();
        console.log(serialdata);
        const inputserialnumber = document.getElementById('serialnumber').value.toString();
        console.log(inputserialnumber);
        // serialdata.match(/inputserialnumber/)
        // serialdata.includes(inputserialnumber)
        if(serialdata.includes(inputserialnumber) == true && inputserialnumber.length == 7 ){
            document.getElementById('validity').innerHTML = "Valid";
            startConfetti(); // from confetti.js
        }else {
            document.getElementById('validity').innerHTML = "Invalid";
            stopConfetti(); // from confetti.js
        }


        //document.getElementById('test').innerHTML = "Valid";
    }


</script>

This is my console output It shows the full csv(currently), & the users input

changed the csv data into to different arrays if that helps: array

& Thanks all in advance for taking the time to reply to my silly question!

EXTRA Clarification:

What I'm trying to do is a validate website checker. So the user inputs their serial through an simple input field. & I have the serials in a csv file with an extra column that has the name matching to the serial. So if the user inputs 1234567 it is present in the CSV file, my current code returns value = true for that. as it is present in the CSV file.

But I want it to return the value next to 1234567 (so in the second Column) instead, in this case "test1". So I can use that value instead of just a standard "Valid" text to be pushed back onto the website.

3 Answers

You can match values of two arrays by their index. In your case, I think it's easiest to use Array.map() to return a transformed array based on the one you loop trough. So for example, if you have two arrays called namesArray and valuesArray, do the following:

const validationResults = valuesArray.map((value, index) => {
  return {
    valid: checkValidity(value), // or whatever your validation function is called
    name: namesArray[index] // match the index of the namesArray with the index of this one (valuesArray)
  };
  // or `return namesArray[index] + ', valid: ' + checkValidity(value)`
});

This loops through the valuesArray, and validationResults will then be an array of what you return per each item in the map function above.

One important note is that this assumes the arrays are both in the same order . If you want to sort them, for instance, do this after this.

Looking up and registering the values in a Map seems like the best answer.

    // ...
    const serialdata = await response.text();
    const seriallookup = new Map();
    // Set all Serial values to Names
    for (let s in serialdata.split("\n")) {
        let data = s.split(',');
        seriallookup.set(data[0], data[1]);
    }

Using this, checking for a serial's existance could be done with .has()

    if (inputserialnumber.length == 7 && seriallookup.has(inputserialnumber)) {

And set to the elements text using

    document.getElementById('validity').innerHTML = serialdata.get(inputserialnumber);

If the .csv file most likely wouldn't change between multiple requests (or if you only send just one request), you should probably initialize and request the data outside of the function.

Thank you all for the feedback. I have not been able to use your suggestions exactly as intended. But I managed to combine the idea's and create a new piece that does the trick for me!

const checkm = document.getElementById('check');
  checkm.addEventListener('click', serialChecker)
  async function serialChecker(){
              const url = 'http://localhost/validator2/naamloos.csv';
              const response = await fetch(url);
              // wait for the request to be completed
              const serialdata = await response.text();
              const table = serialdata.split('\r\n');  

              const serialsArray = [];
              const nameArray = [];

              table.forEach(row =>{
              const column = row.split(',');
              const sArray = column[0]; 
              const nArray = column[1]; 
              
              serialsArray.push(sArray);
              nameArray.push(nArray);
              
            })

            var array1 = serialsArray,
              array2 = nameArray,
              result = [],
              i, l = Math.min(array1.length, array2.length);
              
              for (i = 0; i < l; i++) {
                  result.push(array1[i], array2[i]);
              }
              result.push(...array1.slice(l), ...array2.slice(l));

              function testfunction(array, variable){
                  var varindex = array.indexOf(variable)
                  return array[varindex+1] 
              }
              //calling the function + userinput for serial

              const inputserialnumber = document.getElementById('serialnumber').value.toString();
              console.log(testfunction(result, inputserialnumber))

              if(serialsArray.includes(inputserialnumber) == true && inputserialnumber.length == 7 ){
                document.getElementById('validity').innerHTML = "Valid " + testfunction(result, inputserialnumber);

                startConfetti();
              }else {
                  document.getElementById('validity').innerHTML = "Invalid";

                  stopConfetti();
              }
  }

Hope this can help someone out in having an input field on their website with a .csv file in the backend (possible to have multiple for the user to select with a dropdown box with the async function).

This will check the file & will return the value from the csv that matches the serial!(based on serial number & length of the serial number(7characters))

Related