Reputation: 4616
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.
Upvotes: 0
Views: 1783
Reputation: 54050
I have tried very basic Approcah, but it will help you to understand
<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>
$(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)
})
Function Reference
Upvotes: 4