0
0

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 3 years have passed since last update.

2次元配列の中から特定値の個数を導き出す

Posted at

2次元配列から特定値の個数を見つける良い書き方がないかな、と考えていて
forEachで2重ループするのも考えたのだけど、
できるだけ使いたくないので一行で記述できる方法を考えてみた。

基本的には
1:[].concat(...array) or array.flat()を利用して異次元配列に変換
2:フィルターで特定の値だけの配列に変換
3:lengthで配列の個数を得る

という手順で行いました。

2次元配列の中から特定値の個数を導き出す

// 5*5の二次元配列
const array = [
  [0, 0, 0, 0, 1],
  [0, 1, 0, 2, 0],
  [0, 0, 1, 0, 0],
  [0, 2, 0, 1, 0],
  [0, 0, 0, 0, 1]
];

/* ①スプレッド演算子を使う
- [].concat(...array) : 一次元配列にする
*/
const result1 = 
  [].concat(...array)
  .filter(number => { return number === 2; })
  .length


/* ②flat()を使う IE未対応
- array.flat() : 1次元配列にする
*/
const result2 = 
  array.flat()
  .filter(number => { return number === 1; })
  .length

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?