javascript set内の最大値・最小値を取得する
- 作成日 2022.10.26
- javascript
- javascript

javascriptで、set内の最大値・最小値を取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。まずは「set」を配列化して「Math.max」と「Math.min」を使用します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 106.0.5249.103
set内の最大値・最小値を取得
set内の最大値・最小値を取得するには「set」をスプレッド構文で配列にして「Math.max」で最大値、「Math.min」で最小値を使用します。
const s = new Set([20, 15, 10, 12, 18]);
const min = Math.min(...s);
console.log(min); // 10
const max = Math.max(...s);
console.log(max); // 20
文字列の数値の場合でも機能します。
const s = new Set([20, '05', 10, '030', 18]);
const min = Math.min(...s);
console.log(min); // 5
const max = Math.max(...s);
console.log(max); // 30
文字列が含まれている場合は「NaN」が返ります。
const s = new Set([20, 'aa', 10, '030', 18]);
const min = Math.min(...s);
console.log(min); // NaN
const max = Math.max(...s);
console.log(max); // NaN
-
前の記事
CentOs9 Mysqlのインストール手順 2022.10.25
-
次の記事
javascript エラー「Uncaught ReferenceError: Invalid left-hand side expression in prefix operation」の解決方法 2022.10.26
コメントを書く