Search code examples
javascriptjqueryarraysfunctional-programming

jQuery .map into array


I don't know how I would .map into an array. I want to get all values of children but 2 and then put it into an array format.

Here's the code I'm attempting it with:

$("#schoolSupplies").submit(function() {
    var test = $(":input").not("#numOfSupplies, #submitBtn").map(function() {
        return $(this).val();
    })
    .get()
  .join( "\", \"" );

    console.log(test);
});

And this is the output: Billy", "John

I have been working on this for about an hour and I have no idea how.


Solution

  • The jQuery .get() method returns an Array 1.

    screenshot of jQuery documentation for get method

    If the call to the Array .join() method was removed then test would simply be an array; otherwise test would be a string (since that is what the .join() method returns).

    $("#schoolSupplies").submit(function() {
        var arrayOfValues = $(":input").not("#numOfSupplies, #submitBtn").map(function() {
            return $(this).val();
        })
        .get()
      //.join( "\", \"" ) // calling this returns a string
        ;
        
        console.log('Array.isArray(arrayOfValues): ', Array.isArray(arrayOfValues)?'yes':'no', ' contents of arrayOfValues: ', arrayOfValues);
        return false; //for demonstration purposes, don't submit form normally
    });
    $($("#submitBtn").click());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="schoolSupplies">
      Supply Name: <input id="name" type="text" value="Tables" /><br />
      
      Student Name: <input id="studentName" type="text" value="Bobby"/><br />
      # of Supplies: <input id="numOfSupplies" type="number" value="3" /><br />
      <input type="submit" id="submitBtn" />
      </form>