user1020408
user1020408

Reputation: 45

Populating a two-dimensional array from image groups

I have several images, and I need to be able to group and select them by title, and also manipulate them individually.

My images look like this:

<img src="1.jpg" title="cat">
<img src="2.jpg" title="cat">
<img src="3.jpg" title="cat">
<img src="1.jpg" title="dog">
<img src="2.jpg" title="dog">
<img src="3.jpg" title="dog">
<img src="1.jpg" title="horse">
<img src="2.jpg" title="horse">
<img src="3.jpg" title="horse">

... and so on.

I'm trying to create an array that looks like this:

imgArray = [cat[1,2,3], dog[1,2,3], horse[1,2,3]];

... where the first array level is the group(title), and within each group is an array of the actual elements with matching titles. I need to be able to do things like this:

var imgGroup = imgArray[cat];
doThings(imgGroup)
function doThings(target){
   var pri = target[0], sec = target[1], ter = target[2];
   pri.doThis(); sec.doThat(); ter.doTheotherthing();
});

So far I'm doing this:

img.each(function(){
   var self = $(this),  title = self.attr('title');
   imgArray.push([title, self]) 
   imgArray = $.unique(imgArray) //remove duplicate titles
});

But this is obviously not working and probably for a reason that makes me look stupid :/

Is anyone able to help me with this logic?

Upvotes: 0

Views: 617

Answers (2)

kennebec
kennebec

Reputation: 104760

Why not use class names instead of titles? Then you can handle all the 'horse' elements in a group, using getELementsdByClassName or a query that filters the images by class. Use the titles for unique information...

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150010

I suspect the structure you really need is an object (not an array) where you have a property for each type of animal, and the value of each property is an array of numbers:

var imgObj = {
   "cat" : [1, 2, 3],
   "dog" : [1, 2, 3],
   "horse" : [1, 2, 3]
}

Then you can say:

imgObj["cat"]          // give the array [1,2,3]
imgObj["horse"].length // gives 3
imgObj["dog"][0]       // accesses the first value in the dog array

Except that the way your code is trying to create and use your array/object it seems you want the sub arrays to hold jQuery objects that themselves contain the individual DOM img elements? Still you'd want an object where the properties are arrays.

You didn't tag your question as jQuery, though from your existing code you seem to be using it, so here's how you could create the above struture from your markup:

var imgObj = {};
$("img").each(function() {
   var title = this.title;
   if (!imgObj.hasOwnProperty(title))
       imgObj[title] = [];

   imgObj[title].push($(this));
});

You should then be able to call your existing doThings() function as follows:

doThings(imgObj["cat"]);    // passes just the cat array

Upvotes: 1

Related Questions