array_count_values for JavaScript instead
Asked Answered
O

6

4

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 days but cannot find anything similar? What I want to do is to count the number of times a certain word is being used in an array.

$interfaceA = array($interfaceA_1,$interfaceA_2,$interfaceA_3,$interfaceA_4,$interfaceA_5,$interfaceA_6,$interfaceA_7,$interfaceA_8);       

$interfaceA_array=array_count_values($interfaceA);
$knappsatsA = $interfaceA_array[gui_knappsats];
$touchpanelA = $interfaceA_array[gui_touchpanel];
Obsequent answered 7/3, 2011 at 7:48 Comment(1)
You will need to write your own :)Congruence
T
14

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']);
Trapan answered 7/3, 2011 at 7:52 Comment(1)
Edited: counts should be an object {}, not an Array.Cyclometer
I
9

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.

Illsorted answered 27/7, 2014 at 11:10 Comment(0)
P
6

Try

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

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

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

console.log(count);
Pampas answered 8/7, 2019 at 7:13 Comment(0)
C
2

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;
}
Congruence answered 7/3, 2011 at 8:1 Comment(0)
P
0

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))
Picro answered 20/10, 2018 at 18:3 Comment(0)
R
0

This should work

function array_count_values(array) {
  var tmpArr = {};
  var key = '';
  var t = '';
  var _countValue = function(tmpArr, value) {
    if (typeof value === 'number') {
      if (Math.floor(value) !== value) {
        return;
      }
    } else if (typeof value !== 'string') {
      return;
    }
    if (value in tmpArr && tmpArr.hasOwnProperty(value)) {
      ++tmpArr[value];
    } else {
      tmpArr[value] = 1;
    }
  }

  for (key in array) {
    if (array.hasOwnProperty(key)) {
      _countValue.call(this, tmpArr, array[key]);
    }

  }

  return tmpArr;
}
console.log(array_count_values([12, 43, 12, 43, "null", "null"]));
Rossiter answered 8/6, 2020 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.