33
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで配列の重複している項目の数をカウントする

Last updated at Posted at 2016-09-15

配列で重複している要素数をカウントしたい、と思って調べていると、PHPにはarray_count_valuesという関数があるそうで便利だな、と思いました。

PHP: array_count_values - Manual

ただ、自分はJavaScriptでほしいと思っていたので、調べると、ドンピシャのstack overflowの記事がヒットしたので共有しておきます。

php - array_count_values for JavaScript instead - Stack Overflow

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

非常に分かりやすいですね。自分もこういうのすぐ思いつけるようになりたいです。

追記
npmのパッケージを調べるとcount-array-valuesというのが見つかったので使い勝手優先するならこっちで良さそうです。

count-array-values

33
26
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?