1

I have the following URL:

products?feature_filters[]=&feature_filters[]=on&feature_filters[]=on

From this I need to get an array, something like this:

var feature_filters = [1, 2] 

NOTE: As MightyPork has pointed out, this would be zero-based.. so I would need to reject 0, and keep 1, and 2.

I have successfully employed this example to get URL parameters when they are defined once. However I am not able to parse this set of parameters, created by my app.

Community
  • 1
  • 1
Abram
  • 39,950
  • 26
  • 134
  • 184
  • `var feature_filters = [2, 3]` is javascript. Are you working with node.js or what? Besides, it'd be [1,2] as it's zero based. – MightyPork Dec 13 '14 at 15:35
  • If you look at the number of times feature_filters[] appears in the URL, you can see that the second and third time the parameter value = "on" .. Basically I need to get the values 1 and 2 from this URL in order to utilize them in my app. – Abram Dec 13 '14 at 15:36

1 Answers1

0

You can extend the in your linked answer, to loop through the parameters in the same way, but instead of just returning the first match, build up an object where each property is the name of the querystring entry and contains an array of its value, basically a dictionary of arrays.

Then for a specific key, you can loop through it's array and find which indices are set:

// groups all parameters together into a dictionary-type object
function getUrlParameterGroups()
{
    var sPageURL = window.location.search.substring(1);

    var paramGroups = {};
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var paramParts = sURLVariables[i].split('=');
        var sParameterName = paramParts[0];
        // first time we've seen it - add a blank array
        if(!paramGroups.hasOwnProperty(sParameterName))
        {
            paramGroups[sParameterName] = [];
        }

        // ad to the array
        if(paramParts.length > 1)
        {
            paramGroups[sParameterName].push(paramParts[1]);
        }
        else
        {
            // handle not having an equals (eg y in x=1&y&z=2)
            paramGroups[sParameterName].push('');
        }
    }

    return paramGroups;
}

// gets which indices of the specified parameter have a value set
function getSetUrlParameters(sParameterName)
{
    var arr = getUrlParameterGroups()[sParameterName];
    return arr.reduce(function(previousValue, currentValue, index) {
        if(currentValue != '') { // or if(currentValue == 'on')
            previousValue.push(index);
        }
        return previousValue;
    }, []);
}

var result = getSetUrlParameters('feature_filters[]');
console.log(result);

Working Fiddle

Rhumborl
  • 16,349
  • 4
  • 39
  • 45