Skip to content

Instantly share code, notes, and snippets.

@stugoo
Created May 24, 2012 11:02
Show Gist options
  • Save stugoo/2780833 to your computer and use it in GitHub Desktop.
Save stugoo/2780833 to your computer and use it in GitHub Desktop.
array builder for nesting arrays, checking categories and flange
var items = [];
// We're emulating indexOf, but for objects in the array.
// The function returns an integer (>=0), to the object that matched.
function in_property_array(property, value, arr) {
var i, max = arr.length, current;
for (i = 0; i < max; i++) {
if (arr[i][property] === value) {
return i;
}
}
return false;
}
$('a.reading-list').click(function(){
var el = $(this);
var category = el.data('category');
var id = el.data('id');
var id_index = in_property_array('id', id, items);
var cat_index = in_property_array('category', category, items);
var details = {
title: el.text(),
url: el.attr('href'),
id: id
};
if( id_index !== false ) {
console.log('id exists > do nothing');
// return false;
} else if( cat_index !== false ) {
console.log('category exists');
var cat_details = items[cat_index].detail;
if ( in_property_array('id', id, cat_details) === false ) {
items[cat_index].detail.push( details );
}
} else {
items.push({
"category": category,
"detail": [ details ]
});
}
console.log(items);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment