0
// 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

  • `arrayName[2]` (which means "3rd element of `arrayName` array") is a number `2`. A number doesn't have `length` property – zerkms Jan 22 '14 at 22:14
  • @Pheonixblade9: it's more likely "not clear what you're asking". According to the "expected result" OP doesn't want just a number of unique elements, since it would be 4, not 3 – zerkms Jan 22 '14 at 22:18
  • It's both, really. Both on hold conditions apply here – Codeman Jan 22 '14 at 22:19

4 Answers4

2

To count the number of 2's in the array you can do

var instances = arrayName.filter(function(e) {
    return e===2;
}).length;

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You don't need a lenght. Just reference the value at that index:

alert(arrayName[2]);
Bic
  • 3,141
  • 18
  • 29
0

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

Community
  • 1
  • 1
Codeman
  • 12,157
  • 10
  • 53
  • 91
  • 1
    -1 for plagiarism http://stackoverflow.com/a/1961068/251311 If you "borrow" a solution - be so kind to refer to the original author – zerkms Jan 22 '14 at 22:16
  • @zerkms I marked the question as duplicate and added a reference – Codeman Jan 22 '14 at 22:16
0

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.

Tian Jin
  • 279
  • 1
  • 3
  • 9