How to count Matching values in Array of Javascript
Asked Answered
H

6

1

please tell me any good algorithm/code to get list of unique values from array and count of its occurrence in array. (i am using javascript).

Haemostat answered 9/2, 2010 at 10:38 Comment(1)
Possible duplicate of Counting the occurrences of JavaScript array elementsXylograph
D
1

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(n2) 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 = new Array("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.

Dispart answered 9/2, 2010 at 10:46 Comment(3)
please tell me am i using it correctly: arrtmp.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] is found later in the array if (this[i] === this[j]) j = ++i; } a.push(this[i]); } return a; };Haemostat
@DotNetDeveloper: I've updated my answer with a tested example.Dispart
Where are the counts?Vice
C
2

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 (val in histo) {...}
Cuspidate answered 9/2, 2010 at 11:4 Comment(1)
I like this solution. I especially like that you mentioned the big O speed.Aneto
D
1

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(n2) 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 = new Array("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.

Dispart answered 9/2, 2010 at 10:46 Comment(3)
please tell me am i using it correctly: arrtmp.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] is found later in the array if (this[i] === this[j]) j = ++i; } a.push(this[i]); } return a; };Haemostat
@DotNetDeveloper: I've updated my answer with a tested example.Dispart
Where are the counts?Vice
D
1

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
Dubitable answered 9/2, 2010 at 11:4 Comment(1)
I can confirm that this works, as stereofrog says, you MUST be doing something wrong. +1 stereofrog!Byelection
M
1

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]) return 0;
        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;
}
Metamer answered 9/2, 2010 at 15:22 Comment(0)
C
0

I know this is old post but I was lookimg for a simple solution so I figured I'd post what I worked out for anyone still looking into this

const test = [5, 3, 9, 5, 3, 5, 5]


//This function will return a new array of only the specified value
Array.prototype.unique = function(find) {
return this.filter(x => x == find)
}

//Usage
console.log(test.unique(5)) // returns [5,5,5,5]


//This Function will return the number of occurences in an array
Array.prototype.count = function(find) {
return this.filter(x => x == find).length
}

//Usage
console.log(test.count(5)) // returns 4
Colunga answered 11/2, 2022 at 2:47 Comment(0)
R
0

Same as above but shortly:

const data = [5,25,15,5,34,2,5];
console.log(data.filter(value => value === 5).length)
Rene answered 15/1 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.