Sarfraz
Sarfraz

Reputation: 382746

JS: Get number of same values

Suppose i have this array:

[1, 2, 2, 3, 3, 3, 4]

How do i return an array/object that contains how many times a value appears something like:

{1:1, 2:2:, 3:3, 4:1}

Here is what I have so far:

// sort first
arr.sort();

for (var i = 0, l = arr.length, i < l, i++) {
    // what should go here ???? 
}

Upvotes: 1

Views: 76

Answers (5)

KooiInc
KooiInc

Reputation: 122916

You could use the Array forEeach method:

var freq = {}, arr = [1, 2, 2, 3, 3, 3, 4];
arr.forEach(function(x){
   freq[x] = freq[x] ? freq[x]+1 : 1;
});
//=> freq[1] = 1, freq[2] = 2, freq[3] = 3 and freq[4] = 1
//=> arr is still [1, 2, 2, 3, 3, 3, 4]

Upvotes: 1

Sampson
Sampson

Reputation: 268364

// Our results will be loaded into cont
var cont = {};

// For each number in our value array
for ( var i = 0; i < vals.length; i++ ) {
   // If it's found in the result array
   cont[ vals[i] ]
     // Increment it
     ? cont[ vals[i] ]++
     // Else, set it to 1
     : cont[ vals[i] ] = 1 ;
}

Could be made even simpler using a while loop and variable assignment:

var vals = [1, 2, 2, 3, 3, 3, 4], // Values to cycle through
    cont = {},                    // Object to store results in
    indx = i = -1;                // Index and Counting variables

while ( indx = vals[ ++i ] )      // While a value exists for location i
  cont[ indx ]                    // Check to see if it's in the result object
    ? cont[ indx ]++              // If it is, increment it
    : cont[ indx ] = 1 ;          // If it is not, set it to 1

Upvotes: 3

J0HN
J0HN

Reputation: 26941

No need to sort.

var result = {};
for (var i = 0; i < arr.length; i++){
    if (!result[arr[i]]) {
        result[arr[i]]=0;
    }
     result[arr[i]]+=1;
}

Upvotes: 1

Michael Seibt
Michael Seibt

Reputation: 1346

Here you go!

var arr = [1, 2, 2, 3, 3, 3, 4]; // Sample data
var countings = {}; // Result object
for (var i = 0; i < arr.length; i++) {
    if(countings[(arr[i])] == undefined) countings[(arr[i])] = 0;
    countings[(arr[i])]++;
}

Fiddle goes here.

Upvotes: 1

jbabey
jbabey

Reputation: 46647

what you're looking for is a histogram:

http://jsfiddle.net/jbabey/jdMgp/

var array = [1, 2, 2, 3, 3, 3, 4];
var results = {};

for (var i = 0; i < array.length; i++) {
    if (results.hasOwnProperty(array[i])) {
        results[array[i]]++;
    } else {
        results[array[i]] = 1;
    }
}

console.log(results);​

Upvotes: 2

Related Questions