LoginSignup
0
2

JavaScriptで計算問題を解くためのチートシート

Last updated at Posted at 2023-06-27

概要

  • 練習がてらJavaScript(Node.js)でプログラミングの計算問題を解きたい。
  • データがファイルで読み込むタイプの時でも対応できるようにしている
  • 自分のためのチートシートでしたが、公開します。

チートシート

<基本>

1. 文字列→配列(分割)

const input = "A,B,C,D";
const array = input.split(",");
console.log(array);
// →["A", "B", "C", "D"]

2. 配列→文字列(結合)

const array = ["A", "B", "C", "D"];
const text = array.join("");
console.log(text);
// → ABCD

3. 配列の文字列を全てNumberに

const array = ["1", "2", "3", "4"];
const arrrayNum = array.map((x) => Number(x));
console.log(arrrayNum);
// → [1, 2, 3, 4]

4. 配列のNumberの和

const array = [1, 2, 3, 4];
const sum = .reduce((a, b)=> a + b);
console.log(sum);
// → 10

5. 配列の重複をなくす

const array = [1, 2, 3, 4, 4, 3, 5];
const set = new Set(array);
const setArr = Array.from(set);
console.log(setArr);
// → [1, 2, 3, 4, 5]

6. 配列に追加する

const array = [1, 2, 3, 4, 5];
array.push(6)
console.log(array);
// → [1, 2, 3, 4, 5, 6]

7. 配列を逆順にする

const array = [1, 2, 3, 4, 5];
const reverse = array.reverse();
console.log(reverse);
// → [5, 4, 3, 2, 1]

8. 配列をソートする

const array = [4, 2, 1, 3, 5];
const reverse = array.sort();
console.log(reverse);
// → [1, 2, 3, 4, 5]

9. デカすぎて正しく計算できない数値対応

const bigNum = BigInt(10000000000000000000000);
const twiceNum = bigNum * BigInt(2);
console.log(twiceNum);
// → 20000000000000000000000n
// ※BigIntの結果には語尾にnがつく

9. ファイルのインポート

const fs = require("fs");
const input = fs.readFileSync("(パス名)/01.txt", "utf-8");  // csvも可能

<応用>

<基本>の内容を使ったらできることです。

1. 各位の和

const num = Number(123); // BigInt()も可能
const sum = num.toString().split("").map(x=>Number(x)).reduce((a, b)=> a + b);
console.log(sum);
// → 10

2. 回文数

const num = 12345;
const sum = Number(num.toString().split("").reverse().join("")); // BigInt()も可能
console.log(sum);
// → 54321

3. 任意の位の値取得

const num = 12345;
// 100の位
const hyaku_no_kurai = Number(num.toString().split("")[2])
console.log(hyaku_no_kurai);
// → 3

4. 改行データを配列に分割

const txt = `ABC
DEF
GHI`;
const array = txt.split("\n")
console.log(array);
// → ['ABC', 'DEF', 'GHI']

5. 改行データを一行にする

const txt = `ABC
DEF
GHI`;
// 正規表現で全ての改行をマッチさせ、""に置き換える
const oneLine = txt.replace(/\n/g, "") 
console.log(oneLine);
// → 'ABCDEFGHI'

以上(適宜更新していきます)

0
2
2

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
2