- Day 27:データ処理演習①(前半)
- 商品データの準備:オブジェクトの配列で表現する
- 商品一覧を作る:配列をループして表示する
- 商品検索を作る:名前で商品を探す
- 指定価格以下の商品表示:条件で絞り込む
- 合計金額を計算する:配列の値を足し合わせる
- 4つの機能をまとめて動かすテンプレート(ブラウザで実行可能)
- Day 27 前半のまとめ
- Day 27:データ処理演習①(後半)
- 商品データの再確認:土台となる配列
- 商品一覧:表示ロジックを“部品化”する
- 商品検索:結果が0件のときの振る舞いを決める
- 指定価格以下の商品表示:入力値のチェックを意識する
- 合計金額:部分集合の合計も計算できるようにする
- 4つの機能をまとめて“ツール”として動かすテンプレート
- Day 27 後半のまとめ
Day 27:データ処理演習①(前半)
「商品データを“自由に扱える”感覚を身につける」
Day 27では、これまで学んできた 配列・オブジェクト・条件分岐・ループ を使って、 実務に近い形の「商品データの処理」をまとめて練習していきます。
課題は次の4つです。
- 商品一覧を表示する
- 商品検索をする
- 指定価格以下の商品を表示する
- 合計金額を計算する
ここでは、1つの「商品データ」を軸にして、 「同じデータから、いろいろな切り口で情報を取り出す」 という感覚を育てていきます。
商品データの準備:オブジェクトの配列で表現する
商品データの基本形
まずは、商品データを「オブジェクトの配列」で用意します。
// 商品データの配列(1件が1つの商品オブジェクト)
const products = [
{ id: 1, name: 'ノート', price: 100 },
{ id: 2, name: 'ボールペン', price: 150 },
{ id: 3, name: '消しゴム', price: 80 },
{ id: 4, name: 'シャープペンシル', price: 300 },
{ id: 5, name: '定規', price: 120 },
];
JavaScript- 配列:複数の商品をまとめて管理するための入れ物
- オブジェクト:1つの商品を「id」「name」「price」で表現
この形は、実務でも非常によく使われるデータ構造です。
商品一覧を作る:配列をループして表示する
ステップ1:1件ずつ商品を表示する関数を作る
まずは、1つの商品オブジェクトを受け取って、 その内容をコンソールに表示する関数を作ります。
// 1つの商品を表示する関数
function printProduct(product) {
console.log(`ID: ${product.id}/商品名: ${product.name}/価格: ${product.price}円`);
}
JavaScriptproductは{ id, name, price }を持つオブジェクトです。- テンプレートリテラル(バッククォート)で、見やすい文字列に整えています。
ステップ2:商品一覧を表示する関数を作る
次に、配列 products を受け取って、 全件を表示する関数を作ります。
// 商品一覧を表示する関数
function printProductList(products) {
console.log('--- 商品一覧 ---');
// for...ofで配列を1件ずつ取り出します
for (const product of products) {
printProduct(product); // 1件ずつ表示
}
console.log('--- 商品一覧ここまで ---');
}
// 実行してみます
printProductList(products);
JavaScriptfor...ofで配列をループし、 各要素(商品オブジェクト)をprintProductに渡しています。- 「一覧表示」は、配列をループして1件ずつ処理する という基本パターンです。
商品検索を作る:名前で商品を探す
ステップ1:検索条件を決める
ここでは、 「商品名に特定の文字列が含まれている商品を探す」 という検索を作ります。
例:
- 「ペン」で検索 → 「ボールペン」「シャープペンシル」がヒット
ステップ2:検索関数を作る
// キーワードに部分一致する商品を検索する関数
function searchProducts(products, keyword) {
const result = [];
// 全商品をチェックします
for (const product of products) {
// 商品名にキーワードが含まれているかを判定します
if (product.name.includes(keyword)) {
result.push(product); // 条件に合う商品を結果配列に追加
}
}
return result;
}
// 実行例
const keyword = 'ペン';
const searched = searchProducts(products, keyword);
console.log(`--- 検索結果(キーワード: "${keyword}") ---`);
printProductList(searched);
JavaScriptincludes()は、文字列に特定の部分文字列が含まれているかを判定するメソッドです。- 検索結果は新しい配列
resultに集めて、最後に返しています。 - 「検索」は、条件に合うものだけを新しい配列に集める というパターンです。
指定価格以下の商品表示:条件で絞り込む
ステップ1:価格の上限を決める
ここでは、 「指定した価格以下の商品だけを表示する」 という機能を作ります。
例:
- 150円以下 → ノート(100円)、ボールペン(150円)、消しゴム(80円)、定規(120円)
ステップ2:絞り込み関数を作る
// 指定価格以下の商品だけを抽出する関数
function filterByMaxPrice(products, maxPrice) {
const result = [];
for (const product of products) {
// 価格がmaxPrice以下かどうかを判定します
if (product.price <= maxPrice) {
result.push(product); // 条件に合う商品を結果配列に追加
}
}
return result;
}
// 実行例
const maxPrice = 150;
const filtered = filterByMaxPrice(products, maxPrice);
console.log(`--- ${maxPrice}円以下の商品 ---`);
printProductList(filtered);
JavaScript- 条件は
product.price <= maxPriceというシンプルな比較です。 - 「絞り込み」は、条件に合うものだけを新しい配列に集める という点で、検索と同じパターンです。
合計金額を計算する:配列の値を足し合わせる
ステップ1:合計金額の意味を整理する
ここでは、 「商品配列のすべての価格を足し合わせる」 という処理を作ります。
例:
- ノート(100)+ボールペン(150)+消しゴム(80)+シャープペンシル(300)+定規(120)
- 合計:
100 + 150 + 80 + 300 + 120 = 750
ステップ2:合計金額を計算する関数を作る
// 商品配列の合計金額を計算する関数
function calculateTotalPrice(products) {
let total = 0; // 合計金額を入れる変数(最初は0)
for (const product of products) {
total += product.price; // 各商品の価格を足していきます
}
return total;
}
// 実行例
const totalPrice = calculateTotalPrice(products);
console.log('--- 合計金額 ---');
console.log(`全商品の合計金額は ${totalPrice} 円です。`);
JavaScripttotalを0からスタートし、 ループの中でtotal += product.priceと足し込んでいきます。- 「合計」は、ループしながら1つの変数に値を蓄積する という基本パターンです。
4つの機能をまとめて動かすテンプレート(ブラウザで実行可能)
以下のテンプレートをブラウザで開き、 コンソールで「商品一覧」「商品検索」「価格で絞り込み」「合計金額」を確認してください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Day 27 前半:データ処理演習① テンプレート</title>
</head>
<body>
<h1>Day 27 前半:商品データ処理演習①</h1>
<p>ブラウザのコンソールを開いて、ログを確認してください。</p>
<script>
console.log('--- 商品データの準備 ---');
const products = [
{ id: 1, name: 'ノート', price: 100 },
{ id: 2, name: 'ボールペン', price: 150 },
{ id: 3, name: '消しゴム', price: 80 },
{ id: 4, name: 'シャープペンシル', price: 300 },
{ id: 5, name: '定規', price: 120 },
];
function printProduct(product) {
console.log(`ID: ${product.id}/商品名: ${product.name}/価格: ${product.price}円`);
}
function printProductList(products) {
console.log('--- 商品一覧 ---');
for (const product of products) {
printProduct(product);
}
console.log('--- 商品一覧ここまで ---');
}
console.log('--- 商品一覧を表示 ---');
printProductList(products);
console.log('--- 商品検索(キーワードで部分一致) ---');
function searchProducts(products, keyword) {
const result = [];
for (const product of products) {
if (product.name.includes(keyword)) {
result.push(product);
}
}
return result;
}
const keyword = 'ペン';
const searched = searchProducts(products, keyword);
console.log(`キーワード "${keyword}" の検索結果:`);
printProductList(searched);
console.log('--- 指定価格以下の商品表示 ---');
function filterByMaxPrice(products, maxPrice) {
const result = [];
for (const product of products) {
if (product.price <= maxPrice) {
result.push(product);
}
}
return result;
}
const maxPrice = 150;
const filtered = filterByMaxPrice(products, maxPrice);
console.log(`${maxPrice}円以下の商品:`);
printProductList(filtered);
console.log('--- 合計金額の計算 ---');
function calculateTotalPrice(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}
const totalPrice = calculateTotalPrice(products);
console.log(`全商品の合計金額は ${totalPrice} 円です。`);
console.log('--- Day 27 前半:データ処理演習①の練習が完了しました ---');
</script>
</body>
</html>
Day 27 前半のまとめ
Day 27前半では、
- 商品データを「オブジェクトの配列」で表現する基本形
- 配列をループして「商品一覧」を表示するパターン
- 条件に合う商品だけを集める「検索」「絞り込み」のパターン
- 価格を足し合わせて「合計金額」を計算するパターン
を確認しました。
ここで扱った4つの機能は、 「同じデータから、目的に応じて必要な情報を取り出す」 という点で共通しています。
Day 27後半では、 これらの処理をもう少し発展させて、 ユーザー入力やエラー処理なども絡めながら、 より実務に近い形のデータ処理演習に進んでいきます。
Day 27:データ処理演習①(後半)
「“ただ動くコード”から“使えるツール”へ育てていく」
Day 27後半では、前半で作った
- 商品一覧
- 商品検索
- 指定価格以下の商品表示
- 合計金額
を、もう一歩実務寄りに育てていきます。 ここでは、
- 関数を「再利用しやすい形」に整える
- ユーザー入力(仮想的に)を意識する
- 不正な値が来たときの振る舞いを考える
という視点を加えながら、 「データ処理の基礎パターン」を体に馴染ませていきます。
商品データの再確認:土台となる配列
まずは、前半と同じ商品データを使います。
// 商品データの配列
const products = [
{ id: 1, name: 'ノート', price: 100 },
{ id: 2, name: 'ボールペン', price: 150 },
{ id: 3, name: '消しゴム', price: 80 },
{ id: 4, name: 'シャープペンシル', price: 300 },
{ id: 5, name: '定規', price: 120 },
];
JavaScriptこの配列を「1つのデータベース」と見立てて、 いろいろな処理を組み合わせていきます。
商品一覧:表示ロジックを“部品化”する
一覧表示関数を「どこからでも使える部品」にする
前半で作った一覧表示を、 他の機能からも使い回せるようにしておきます。
// 1件の商品を表示する関数
function printProduct(product) {
console.log(`ID: ${product.id}/商品名: ${product.name}/価格: ${product.price}円`);
}
// 商品一覧を表示する関数
function printProductList(products) {
console.log('--- 商品一覧 ---');
for (const product of products) {
printProduct(product);
}
console.log('--- 商品一覧ここまで ---');
}
JavaScriptここで大事なのは、
「配列を渡せば、その中身を全部表示してくれる」
という “約束” を関数に持たせることです。
この約束があると、
- 検索結果を表示するとき
- 絞り込み結果を表示するとき
にも、同じ printProductList を使い回せます。
商品検索:結果が0件のときの振る舞いを決める
検索関数の基本形
前半で作った検索関数は次のような形でした。
function searchProducts(products, keyword) {
const result = [];
for (const product of products) {
if (product.name.includes(keyword)) {
result.push(product);
}
}
return result;
}
JavaScript「ヒットしなかったとき」を丁寧に扱う
検索結果を表示するとき、 0件だった場合のメッセージも用意しておくと、 ツールとしての使い勝手がよくなります。
function printSearchResult(products, keyword) {
const result = searchProducts(products, keyword);
console.log(`--- 検索結果(キーワード: "${keyword}") ---`);
if (result.length === 0) {
console.log('該当する商品はありませんでした。');
} else {
printProductList(result);
}
console.log('--- 検索結果ここまで ---');
}
// 実行例
printSearchResult(products, 'ペン'); // ヒットあり
printSearchResult(products, '消し'); // ヒットあり
printSearchResult(products, '鉛筆'); // ヒットなし
JavaScript- 「0件のときにどう振る舞うか」を決めることは、 実務でも非常に重要です。
- ただ「空の配列を返す」だけでなく、 ユーザーにとってわかりやすいメッセージを出すことで、 ツールとしての完成度が上がります。
指定価格以下の商品表示:入力値のチェックを意識する
絞り込み関数の基本形
前半で作った絞り込み関数は次のような形でした。
function filterByMaxPrice(products, maxPrice) {
const result = [];
for (const product of products) {
if (product.price <= maxPrice) {
result.push(product);
}
}
return result;
}
JavaScript「おかしな値」が来たときの振る舞いを決める
例えば、maxPrice に負の値や文字列が渡される可能性を考えます。
filterByMaxPrice(products, -100); // 本来ありえない
filterByMaxPrice(products, 'abc'); // 数値ではない
JavaScriptこうしたケースに備えて、 簡単なチェックを入れておくと安全です。
function printFilteredByMaxPrice(products, maxPrice) {
console.log(`--- ${maxPrice}円以下の商品 ---`);
// maxPriceが数値かどうかをチェックします
if (typeof maxPrice !== 'number' || Number.isNaN(maxPrice) || maxPrice < 0) {
console.log('価格の指定が不正です。0以上の数値を指定してください。');
console.log('--- 表示を中止します ---');
return;
}
const result = filterByMaxPrice(products, maxPrice);
if (result.length === 0) {
console.log('該当する商品はありませんでした。');
} else {
printProductList(result);
}
console.log('--- 指定価格以下の商品表示ここまで ---');
}
// 実行例
printFilteredByMaxPrice(products, 150); // 正常
printFilteredByMaxPrice(products, -100); // 不正値
printFilteredByMaxPrice(products, 'abc'); // 不正値
JavaScript- 「不正な入力が来たときにどうするか」を決めることは、 セキュリティや安定性の観点からも重要です。
- ここではシンプルに「メッセージを出して処理を中止する」という方針にしています。
合計金額:部分集合の合計も計算できるようにする
合計金額関数の基本形
前半で作った合計金額関数は次のような形でした。
function calculateTotalPrice(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}
JavaScript「絞り込み結果の合計」を計算する
この関数は、 「全商品の合計」だけでなく、 「検索結果の合計」「指定価格以下の商品の合計」にも使えます。
function printTotalPrice(products) {
const total = calculateTotalPrice(products);
console.log(`合計金額:${total} 円`);
}
// 実行例:全商品の合計
console.log('--- 全商品の合計金額 ---');
printTotalPrice(products);
// 実行例:150円以下の商品だけの合計
const filtered = filterByMaxPrice(products, 150);
console.log('--- 150円以下商品の合計金額 ---');
printTotalPrice(filtered);
JavaScript- 「合計を計算する関数」を1つ作っておけば、 どんな部分集合にも使い回せます。
- こうした “汎用的な部品” を意識して作ることが、 実務での生産性につながっていきます。
4つの機能をまとめて“ツール”として動かすテンプレート
以下のテンプレートをブラウザで開き、 コンソールで「商品一覧」「検索」「価格絞り込み」「合計金額」を 一連の流れとして確認してください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Day 27 後半:データ処理演習① 練習テンプレート</title>
</head>
<body>
<h1>Day 27 後半:商品データ処理演習①(実務寄りバージョン)</h1>
<p>ブラウザのコンソールを開いて、ログを確認してください。</p>
<script>
console.log('--- 商品データの準備 ---');
const products = [
{ id: 1, name: 'ノート', price: 100 },
{ id: 2, name: 'ボールペン', price: 150 },
{ id: 3, name: '消しゴム', price: 80 },
{ id: 4, name: 'シャープペンシル', price: 300 },
{ id: 5, name: '定規', price: 120 },
];
function printProduct(product) {
console.log(`ID: ${product.id}/商品名: ${product.name}/価格: ${product.price}円`);
}
function printProductList(products) {
console.log('--- 商品一覧 ---');
for (const product of products) {
printProduct(product);
}
console.log('--- 商品一覧ここまで ---');
}
console.log('--- 商品一覧を表示 ---');
printProductList(products);
console.log('--- 商品検索(結果0件も考慮) ---');
function searchProducts(products, keyword) {
const result = [];
for (const product of products) {
if (product.name.includes(keyword)) {
result.push(product);
}
}
return result;
}
function printSearchResult(products, keyword) {
const result = searchProducts(products, keyword);
console.log(`--- 検索結果(キーワード: "${keyword}") ---`);
if (result.length === 0) {
console.log('該当する商品はありませんでした。');
} else {
printProductList(result);
}
console.log('--- 検索結果ここまで ---');
}
printSearchResult(products, 'ペン'); // ヒットあり
printSearchResult(products, '鉛筆'); // ヒットなし
console.log('--- 指定価格以下の商品表示(入力チェック付き) ---');
function filterByMaxPrice(products, maxPrice) {
const result = [];
for (const product of products) {
if (product.price <= maxPrice) {
result.push(product);
}
}
return result;
}
function printFilteredByMaxPrice(products, maxPrice) {
console.log(`--- ${maxPrice}円以下の商品 ---`);
if (typeof maxPrice !== 'number' || Number.isNaN(maxPrice) || maxPrice < 0) {
console.log('価格の指定が不正です。0以上の数値を指定してください。');
console.log('--- 表示を中止します ---');
return;
}
const result = filterByMaxPrice(products, maxPrice);
if (result.length === 0) {
console.log('該当する商品はありませんでした。');
} else {
printProductList(result);
}
console.log('--- 指定価格以下の商品表示ここまで ---');
}
printFilteredByMaxPrice(products, 150); // 正常
printFilteredByMaxPrice(products, -100); // 不正値
console.log('--- 合計金額の計算(部分集合にも対応) ---');
function calculateTotalPrice(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}
function printTotalPrice(products, label) {
const total = calculateTotalPrice(products);
console.log(`${label}の合計金額は ${total} 円です。`);
}
printTotalPrice(products, '全商品');
const filtered = filterByMaxPrice(products, 150);
printTotalPrice(filtered, '150円以下の商品');
console.log('--- Day 27 後半:データ処理演習①の練習が完了しました ---');
</script>
</body>
</html>
Day 27 後半のまとめ
Day 27後半では、
- 一覧表示・検索・絞り込み・合計計算を「再利用しやすい関数」として整理したこと
- 検索結果が0件のときや、指定価格が不正なときなど、 「想定外のケース」に対する振る舞いをコードで決めたこと
- 同じ合計関数を、全商品だけでなく部分集合(絞り込み結果)にも使い回すことで、 汎用的な部品として育てていく感覚
を確認しました。
ここまで来ると、 「商品データを渡せば、いろいろな切り口で情報を取り出せる小さなツール」 が手元にできあがっています。
この「データ処理のパターン」は、 ユーザー一覧・ToDo一覧・ログデータなど、 ほぼすべての実務データに応用できますので、 ぜひ何度も書き換えながら、自分の手に馴染ませていってください。
