Skip to content Skip to sidebar Skip to footer

Array_count_values For JavaScript Instead

I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searching for

Solution 1:

Why not simply create a new javascript array "counts" Iterate over original array, and increament the count of "counts" for keys encountered in the array. http://jsfiddle.net/4t28P/1/

var myCurrentArray = new Array("apple","banana","apple","orange","banana","apple");

var counts = {};

for(var i=0;i< myCurrentArray.length;i++)
{
  var key = myCurrentArray[i];
  counts[key] = (counts[key])? counts[key] + 1 : 1 ;

}

alert(counts['apple']);
alert(counts['banana']);

Solution 2:

Another elegant solution would be to use Array.prototype.reduce. Given:

var arr = new Array("apple","banana","apple","orange","banana","apple");

You can just run reduce on it:

var groups = 
  arr.reduce(function(acc,e){acc[e] = (e in acc ? acc[e]+1 : 1); return acc}, {});

Finally you can check the result:

groups['apple'];
groups['banana'];

In the sample above reduce takes two parameters:

  1. a function (anonymous here) taking an accumulator (initialized from the second argument of reduce), and the current array element
  2. the initial value of the accumulator

Whatever the function returns, it will be used as the accumulator value in the next call.

From a type perspective, whatever the type of the array elements, the type of the accumulator must match the type of the second argument of reduce (initial value), and the type of the return value of the anonymous function. This will also be the type of the return value of reduce.


Solution 3:

How about this:

function arrayCountValues (arr) {
    var v, freqs = {};

    // for each v in the array increment the frequency count in the table
    for (var i = arr.length; i--; ) { 
        v = arr[i];
        if (freqs[v]) freqs[v] += 1;
        else freqs[v] = 1;
    }

    // return the frequency table
    return freqs;
}

Solution 4:

Try

a.reduce((a,c)=> (a[c]=++a[c]||1,a) ,{});

let a= ["apple","banana","apple","orange","banana","apple"];

let count= a.reduce((a,c)=> (a[c]=++a[c]||1,a) ,{});

console.log(count);

Solution 5:

let snippet = "HARRY POTTER IS A SERIES OF FANTASY NOVELS WRITTEN BY BRITISH AUTHOR J. K. ROWLING. THE NOVELS CHRONICLE" +
    " THE LIVES OF A YOUNG WIZARD, HARRY POTTER , AND HIS FRIENDS HERMIONE GRANGER AND RON WEASLEY, ALL OF WHOM ARE " +
    " STUDENTS AT HOGWARTS SCHOOL OF WITCHCRAFT AND WIZARDRY";
    
String.prototype.groupByWord = function () {
    let group = {};
    this.split(" ").forEach(word => {
        if (group[word]) {
            group[word] = group[word] + 1;
        } else {
            group[word] = 1;
        }
    });
    return group;
};


let groupOfWordsByCount = snippet.groupByWord();
console.log(JSON.stringify(groupOfWordsByCount,null, 4))

Post a Comment for "Array_count_values For JavaScript Instead"