0

I have a grid of products, and I'm trying to build a dynamic filtering system by assigning each of them data attributes (data-category="" data-department="" data-color="" etc). I need to output a ul of each of these data attributes containing the only the unique options (so "Small, Medium, Large" even though there are multiple instances of each, and some products may have more than one (pipe separated) attribute)

Example:

<div data-category="shorts" data-size="large" data-color="blue"></div> 
<div data-category="shorts" data-size="small|medium|large" data-color="green"></div>
<div data-category="shorts" data-size="small" data-color="green|red"></div>
<div data-category="shirts" data-size="medium" data-color="blue"></div>
<div data-category="sunglasses" data-color="black"></div>

For this data I'm trying to get three lists,

Category: shorts, shirts, sunglasses
Size: large, medium, small
Color: blue, green, red

And stick them into lists elements.

2
  • is it a theoretical question?? Commented Apr 18, 2012 at 4:34
  • Added an example, the code I've already built is so ugly and half baked that I don't wanna even copy and paste it. Commented Apr 18, 2012 at 4:40

1 Answer 1

4

I have tried very basic Approcah, but it will help you to understand

HTML

<div data-category="shorts" data-size="large" data-color="blue"></div> 
<div data-category="shorts" data-size="large" data-color="green"></div>
<div data-category="shorts" data-size="small" data-color="red"></div>
<div data-category="shirts" data-size="medium" data-color="blue"></div>
<div data-category="sunglasses" data-color="black"></div>

jQuery

$(function(){
     var output =[];
     var $cat =[]; 
     var $size = [];
     var $color =[];
    $('div').map(function (i){
        
        if( typeof $(this).data('category') == 'string') 
            $cat[i] = $(this).data('category')
        if( typeof $(this).data('size') == 'string') 
            $size[i] = $(this).data('size')
        if( typeof $(this).data('color') == 'string') 
        $color[i] = $(this).data('color');

    });
    output.push($.unique($cat),$.unique($size),$.unique($color));
    console.log(output); //or use alert(output)

})

DEMO

Function Reference

$.map

$.unique

$.data

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped me quite a bit. Apologies for the delay in accepting your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.