开发者

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 days but cannot find anything similar? What I want to do is开发者_StackOverflow 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];


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']);


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.


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);


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;
}


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))


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"]));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜