javascript 配列からn番ずつ値を取得する
- 作成日 2022.10.20
- javascript
- javascript

javascriptで、配列からn番ずつ値を取得するサンプルコードを記述してます。
環境
- OS windows11 pro 64bit
- ブラウザ chrome 106.0.5249.103
配列からn番ずつ値を取得
配列からn番ずつ値を取得するには、for文でインデックスに指定する変数を「n」として加算します。
function n(arr, nth) {
const result = [];
for (let i = 0; i < arr.length; i += nth) {
result.push(arr[i]);
}
return result;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log( n( arr, 2 ) );
// [1, 3, 5, 7, 9]
console.log( n( arr, 3 ) );
// [1, 4, 7, 10]
「filter」を使用しても同じことが可能です。
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log( arr.filter( function(v,i){return (i % 2 === 0) } ) )
// [1, 3, 5, 7, 9]
console.log( arr.filter( function(v,i){return (i % 3 === 0) } ) )
// [1, 4, 7, 10]
サンプルコード
以下は、
「実行」ボタンをクリックすると、用意した配列から2つずつの間隔で値を取得して表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
const hoge = () => {
// ランダムな「0~9」までの5個の配列を用意
const arr = Array(5).fill().map(x => ~~(Math.random() * 10));
disp(arr, "foo");
disp(arr.filter( (v,i) => i % 2 === 0 ), "fuga");
}
//フロントに表示する関数
const disp = (arr, id) => {
let text = [];
arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-blue-500 text-lg mr-auto">元の配列</h1>
<ul id="foo" class="font-semibold text-lg mr-auto"></ul>
<h1 class="font-semibold text-blue-500 text-lg mr-auto">実行結果</h1>
<ul id="fuga" class="font-semibold text-lg mr-auto"></ul>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
取得されていることが確認できます。

-
前の記事
WinSCP コマンドラインに移動するショートカットキー 2022.10.20
-
次の記事
GAS googleドライブ内の全てのフォルダ名を取得する 2022.10.20
コメントを書く