Javascript. How to count the number of specific elements in an array

Sometime we need to count, how many elements there are in an array of Javascript, but specific elements, for example if you have an array like this:

[1, 2, 3, 5, 2, 8, 9, 2]

Then you need to know how many elements there are of the number 2, the easy form maybe can be, if you create a cycle to count each one elements and writing a conditional with the element to compare if exists or not, look this:

var count = 0;
for(var i = 0; i < array.length; ++i){
    if(array[i] == 2)
        count++;
}

If you want beautify this, maybe you can create a method with parameters, something like this:

function countEelements(element,array)
{
var count = 0;
for(var i = 0; i < array.length; ++i){
    if(array[i] == element)
        count++;
}
return count;
}

that is better, but in Javascript exists a method called filter in the arrays.

The explanation is:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Then if you write something like this:

var count = array.filter(function(x){return x==2}).length

You will get the total of elements of an array, that is very easy.

 

Programing a app to send massive emails

I know the following is not an app (app mobile, app web,.. ) it is a little program to PC, but in this days I’m not sure how to say it, whatever.

In my work we needed a way to send emails from a list, but we didn’t not want to use an external service like mailchimp for example, then we need a simple way to send those emails.

The requeriments

The email’s list will be in csv format, looks like this:

email1@email.com,Jon Doe

emial2@email.com, Rick Doe

Why need two fields? because we need into the email a greeting, for example:

Hi Jon Doe

Loremp ipsum

So each email will have the name of the person.

Continue reading Programing a app to send massive emails