user1211133
user1211133

Reputation:

How to find the count of images that have same file name?

Can you please help me how to find the no.of images for same file name,

 var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png",
              "Rabbit.png","Parrot.png"];

here I have 7 images in the array... I need count like..

               Cat:1   
               Parrot :2
               Penguin:1 

Please give me the suggestion

Thanks, Rajasekhar

Upvotes: 3

Views: 275

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382132

The usual solution is to use an object as a map to make the link between the keys (name of the files) and the count :

var count = {};
for (var i=images.length; i-->0;) {
   var key = images[i].split(".")[0]; // this makes 'Parrot' from 'Parrot.png'
   if (count[key]) count[key]++;
   else count[key] = 1;
}

Then you have, for example count['Parrot'] == 2

Demonstration : http://jsfiddle.net/tS6gY/

If you do console.log(count), you'll see this on the console (Ctrl+Uppercase+i on most browsers) :

enter image description here

EDIT about the i--> as requested in comment :

for (var i=images.length; i-->0;) {

does about the same thing than

for (var i=0; i<images.length; i++) {

but in the other directions and calling only one time the length of the array (thus being very slightly faster, not in a noticeable way in this case).

This constructs is often used when you have a length of iteration that is long to compute and you want to do it only once.

About the meaning of i--, read this.

i-->0 can be read as :

  • decrements i
  • checks that the value of i before decrement is strictly positive (so i used in the loop is positive or zero)

Upvotes: 4

Maksim Vi.
Maksim Vi.

Reputation: 9225

Not sure about efficiency, but this should do:

var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png","Rabbit.png","Parrot.png"];

images.forEach(function(img){
    var count = 0;
    images.forEach(function(image, i){
        if(img === image){
            delete images[i];
            count++;
        }
    });
    console.log(img, count);          
});

DEMO

Upvotes: 1

gabitzish
gabitzish

Reputation: 9691

You can keep unique keys in an array and use another array for counting the frequency:

var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png","Rabbit.png","Parrot.png"]; 
var counts = [];
var keys = [];

for (i = 0; i < images.length; i++){
    if (!counts[images[i]]) {
        counts[images[i]] = 0;
        keys.push(images[i]);
    }
    counts[images[i]]++;
}

for (i = 0; i < keys.length; i++) alert(keys[i] + " : " + counts[keys[i]]);
​

Here is a demo : http://jsfiddle.net/e5zFC/1/

Upvotes: 0

Related Questions