How To Count Matching Values In Array Of Javascript
Solution 1:
Use an object as an associative array:
var histo = {}, val;
for (var i=0; i < arr.length; ++i) {
val = arr[i];
if (histo[val]) {
++histo[val];
} else {
histo[val] = 1;
}
}
This should be at worst O(n*log(n)), depending on the timing for accessing object properties. If you want just the strings, loop over the object's properties:
for (valin histo) {...}
Solution 2:
For a method that will strip the duplicates from an array and returns a new array with the unique values, you may want to check the following Array.unique implementation. With an O(n) complexity, it is certainly not the quickest algorithm, but will do the job for small unsorted arrays.
It is licensed under GPLv3, so I should be allowed to paste the implementation here:
// **************************************************************************// Copyright 2007 - 2009 Tavs Dokkedahl// Contact: http://www.jslab.dk/contact.php//// This file is part of the JSLab Standard Library (JSL) Program.//// JSL is free software; you can redistribute it and/or modify// it under the terms of the GNU General Public License as published by// the Free Software Foundation; either version 3 of the License, or// any later version.//// JSL is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU General Public License for more details.//// You should have received a copy of the GNU General Public License// along with this program. If not, see <http://www.gnu.org/licenses/>.// ***************************************************************************
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
if (this[i] === this[j]) // If this[i] is found later in the array
j = ++i;
}
a.push(this[i]);
}
return a;
};
You would be able to use it as follows:
var myArray =newArray("b", "c", "b", "a", "b", "g", "a", "b");
myArray.unique(); //returns: ["c", "g", "a", "b"]
You may want to tweak the above to somehow append the number of occurrences of each value.
Solution 3:
a straightforward way is to loop over the array once and count values in a hash
a = [11, 22, 33, 22, 11];
count = {}
for(var i = 0; i < a.length; i++)
count[a[i]] = (count[a[i]] || 0) + 1
the "count" would be like this { 11: 2, 22: 2, 33: 1 }
for sorted array the following would be faster
a = [11, 11, 11, 22, 33, 33, 33, 44];
a.sort()
uniq = [];
len = a.length
for(var i = 0; i < len;) {
for(var k = i; k < len && a[k] == a[i]; k++);
if(k == i + 1) uniq.push(a[i])
i = k
}
// here uniq contains elements that occur only once in a
Solution 4:
This method works for arrays of primitives - strings, numbers, booleans,
and objects that can be compared(like dom elements)
Array.prototype.frequency= function(){
var i= 0, ax, count, item, a1= this.slice(0);
while(i<a1.length){
count= 1;
item= a1[i];
ax= i+1;
while(ax<a1.length && (ax= a1.indexOf(item, ax))!= -1){
count+= 1;
a1.splice(ax, 1);
}
a1[i]+= ':'+count;
++i;
}
return a1;
}
var arr= 'jgeeitpbedoowknnlfiaetgetatetiiayolnoaaxtek'.split('');
var arrfreq= arr.frequency();
The return value is in the order of the first instance of each unique element in the array.
You can sort it as you like- this sorts from highest to lowest frequency:
arrfreq.sort(function(a, b){
a= a.split(':');
b= b.split(':');
if(a[1]== b[1]){
if(a[0]== b[0]) return0;
return a[0]> b[0]? 1: -1;
}
return a[1]> b[1]? -1: 1;
});
arrfreq now returns(Array): ['e:7','t:6','a:5','i:4','o:4','n:3','g:2','k:2','l:2','b:1','d:1','f:1','j:1','p:1','w:1','x:1','y:1']
mustn't leave out IE:
Array.prototype.indexOf= Array.prototype.indexOf ||
function(what, index){
index= index || 0;
var L= this.length;
while(index< L){
if(this[index]=== what) return index;
++index;
}
return -1;
}
Post a Comment for "How To Count Matching Values In Array Of Javascript"