// for example
var arrayName = [1, 2, 2, 3, 4, 2];
alert ( arrayName[2].length ); // undefined
What I want is
alert ( arrayName[2].length ); // 3
Or any other way .. thank you
// for example
var arrayName = [1, 2, 2, 3, 4, 2];
alert ( arrayName[2].length ); // undefined
What I want is
alert ( arrayName[2].length ); // 3
Or any other way .. thank you
You don't need a lenght. Just reference the value at that index:
alert(arrayName[2]);
Just add this to your array prototype and you can return a unique subset from the array:
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
This is a duplicate of Unique values in an array
Apparently, you are mixing the concept of the index of an array with the actual element of that array.
In short, arrayName[2].length returns the length of the second element. The second element in this case is 2, its length being undefined.
While a good approach for achieving your goal is to use the library underscore:
arr = [1,2,2,2,3];
function countDuplicate(arr, dup) {
return (_.filter(arr, function(num){
return num == dup;
})).length;
}
console.log(countDuplicate(arr, 2));
The fiddle is available here.