Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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)
like image 60
Denys Séguret Avatar answered Jan 02 '26 17:01

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!