LoginSignup
0
0

More than 3 years have passed since last update.

【Javascript】配列から特定の値のインデックスを全部取得する

Posted at

1, 目的

以下の配列から、4という要素が何番目にあるかを全部取得したい。

app.js
const counts = [4,4,3,2,1,4,5,5,4,4,4,4];

2, まず

app.js
counts.indexOf(4)
// 0が取得できる

これで先頭から検索して最初の1つは取れる。
一括して取りたいがうまい方法が見つからない。

3, 次に

app.js
counts.indexOf(4,2)
// 5が取得できる

第二引数で範囲を指定できるので、上記のように書けば2番目以降から検索することができる。
したがって、

app.js
index1 = counts.indexOf(4)
index2 = counts.indexOf(4,index1+1)
// 0、1が取得できる

これで頭から順に2つ取得できる。

4,というわけで

これらをループさせる。

(1) 4の数を数える

app.js
const array4 = counts.filter((count) => {
    return count === 4
}).length

filterメソッドで4だけの配列を作ってlengthで数える

(2) 最初だけcounts.indexOf(4)で取得する

app.js
index_4s = []
index_4 = counts.indexOf(4)
index_4s.push(index_4);

(3) それ以降は4の数−1回ループ

app.js

for (let i = 0 ; i < array4-1; i += 1) {
    index_4 = counts.indexOf(4,index_4+1)
index_4s.push(index_4);
}
// => [0, 1, 5, 8, 9, 10, 11]
0
0
3

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