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.

 

How to clone an object in JavaScript

In JavaScript the assignation of the objects always is through references, for example:

var ob1 = {a:'hi'};

var ob2 = ob1;

If you print this, It show the following:

console.log(ob1);

console.log(ob2);

{ a: 'hi' }

{ a: 'hi' }

What happend if you modify ob2? For example:

ob2.a = 'hi ob2';

Now I’ll print the value of both of them

console.log(ob1);

console.log(ob2);

The result is:

{ a: 'hi ob2' }

{ a: 'hi ob2' }

The value of both is the same, because the value of ob2 is the reference to ob1,  then how we can have two objects diferents, or exactly how to clone an object?.

That is very simple, you just need convert this object to string and convert it to object again.

var ob1 = {a:'hi'};

var ob2 = JSON.parse(JSON.stringify(ob1));

With this, now you have differents objects, if you modify ob2, this change does not affect to object ob1.

Very simple.