回答編集履歴

4

fix

2022/11/22 05:12

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -47,7 +47,7 @@
47
47
  // 'string-番号'という文字列のみに絞る → 文字列の数字を数値化する → 昇順に並び替える
48
48
  const numbers = strArr.filter(str => str.match(/^string-\d+$/))
49
49
                .map(str => Number(str.replace(/^string-/, '')))
50
- .sort((a, b) => a - b); // [1, 2, 3, 5]
50
+ .sort((a, b) => a - b); // [1, 2, 3, 5]
51
51
 
52
52
  const minSkippedNum = getMinSkippedNum(numbers); // 4
53
53
  const uniqueString = `string-${minSkippedNum}`;

3

ついか

2022/11/22 05:11

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -37,3 +37,28 @@
37
37
  const uniqueString = `string-${maxNum + 1}`;
38
38
  console.log(uniqueString); // 'string-6'
39
39
  ```
40
+
41
+ # スキップされた最小の数値を求める方法
42
+ 追加質問文です。
43
+
44
+ ```javascript
45
+ const strArr = ['string-1', 'string-005', 'dummy', 'string-2', 'string-3', 'dummy dummy'];
46
+
47
+ // 'string-番号'という文字列のみに絞る → 文字列の数字を数値化する → 昇順に並び替える
48
+ const numbers = strArr.filter(str => str.match(/^string-\d+$/))
49
+               .map(str => Number(str.replace(/^string-/, '')))
50
+ .sort((a, b) => a - b); // [1, 2, 3, 5]
51
+
52
+ const minSkippedNum = getMinSkippedNum(numbers); // 4
53
+ const uniqueString = `string-${minSkippedNum}`;
54
+ console.log(uniqueString); // 'string-4'
55
+
56
+
57
+ // 配列の中の、スキップされた最小の数値を戻す関数
58
+ function getMinSkippedNum(numberArr) {
59
+ for (let i=0; i<numberArr.length; i++) {
60
+ const sequenceNum = i+1;
61
+ if (numbers[i] !== sequenceNum) return sequenceNum;
62
+ }
63
+ }
64
+ ```

2

tyousei

2022/11/22 02:49

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -28,7 +28,7 @@
28
28
 
29
29
  // 'string-番号'という文字列のみに絞る → 文字列の数字を数値化する
30
30
  const numbers = strArr.filter(str => str.match(/^string-\d+$/))
31
-              .map(str => Number(str.replace(/^string-/, ''))); // [1, 5, 2, 3];
31
+               .map(str => Number(str.replace(/^string-/, ''))); // [1, 5, 2, 3];
32
32
 
33
33
  // 最大値を取得
34
34
  const maxNum = Math.max(...numbers); // 5

1

tuika

2022/11/22 02:48

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -1,3 +1,5 @@
1
+ # 要素数から次の番号を決める方法
2
+
1
3
  絶対に連番(番号がスキップされない)のであれば以下の方法でできます。
2
4
 
3
5
  ### 考え方
@@ -17,3 +19,21 @@
17
19
  const uniqueString = `string-${numberedStrings.length + 1}`;
18
20
  console.log(uniqueString); // 'string-4'
19
21
  ```
22
+
23
+ # 最大値から次の番号を決める方法
24
+ コメントにて、番号がスキップされることや、`string-005`のように変則的な数字が使用される可能性があるということで、それらを考慮したコードです。
25
+
26
+ ```javascript
27
+ const strArr = ['string-1', 'string-005', 'dummy', 'string-2', 'string-3', 'dummy dummy'];
28
+
29
+ // 'string-番号'という文字列のみに絞る → 文字列の数字を数値化する
30
+ const numbers = strArr.filter(str => str.match(/^string-\d+$/))
31
+              .map(str => Number(str.replace(/^string-/, ''))); // [1, 5, 2, 3];
32
+
33
+ // 最大値を取得
34
+ const maxNum = Math.max(...numbers); // 5
35
+
36
+ // maxNum + 1が次の数字
37
+ const uniqueString = `string-${maxNum + 1}`;
38
+ console.log(uniqueString); // 'string-6'
39
+ ```