JavaScript 的 array_count_values

发布于 2024-10-20 15:26:39 字数 435 浏览 1 评论 0原文

我有以下 PHP 脚本,现在我需要在 JavaScript 中做同样的事情。 JavaScript 中是否有一个与 PHP 函数类似的函数,我已经搜索了好几天但找不到类似的东西?我想要做的是计算某个单词在数组中使用的次数。

$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];

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

柠北森屋 2024-10-27 15:26:39

为什么不简单地创建一个新的 javascript 数组“counts”
迭代原始数组,并增加数组中遇到的键的“计数”计数。
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']);

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']);
焚却相思 2024-10-27 15:26:39

另一个优雅的解决方案是使用 Array.prototype.reduce。
给定:

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

您可以对其运行reduce

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

最后您可以检查结果:

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

在上面的示例中,reduce采用两个参数:

  1. 一个函数(此处匿名)采用累加器(从reduce的第二个参数初始化),当前数组元素
  2. 累加器的初始值

无论函数返回什么,它都将在下一次调用中用作累加器值。

从类型角度来看,无论数组元素的类型是什么,累加器的类型都必须与reduce第二个参数(初始值)的类型以及匿名函数的返回值的类型匹配。
这也将是reduce返回值的类型。

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.

还不是爱你 2024-10-27 15:26:39

尝试

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

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

鸠魁 2024-10-27 15:26:39

这个怎么样:

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

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;
}
谈下烟灰 2024-10-27 15:26:39
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))

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

情丝乱 2024-10-27 15:26:39

这应该有效

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文