LoginSignup
1
0

More than 1 year has passed since last update.

JavaScript の文字列・配列・オブジェクト操作

Last updated at Posted at 2023-04-05

自分用にちまちま書いていたメモです。

文字列を配列に変換

// Array.fromを使うパターン
const str = 'ABC'
let arr = Array.from(str)
console.log(arr)
// [ 'A', 'B', 'C' ]

// split で分割するパターン
const str = 'ABC'
let arr = str.split('')
console.log(arr)
// [ 'A', 'B', 'C' ]

文字列が含まれているかどうか

const char = "a"
const str = "abc"

str.includes(char)  // true

変数を利用した置換や正規表現の処理を行う

// new RegExp() を使うことで、変数を利用した置換や正規表現処理が行える

const str = 'abcde'

const char = new RegExp('ab')
console.log(str.replace(char, ''))
// cde

const char2 = new RegExp('a.c')
console.log(str.replace(char2, ''))
// de

配列を昇順にソート

  array.sort((a, b) =>  a - b);

配列を降順にソート

  array.sort((a, b) =>  b - a);

二次元配列を昇順にソート

// それぞれ2つの値を持つ二次元配列を、2番目の値を基準にソートする
const arr = [['A', 3], ['C', 1], ['B', 2]]
const result = arr.sort((a, b) => a[1] - b[1])
console.log(result)

// [[ 'C', 1 ], [ 'B', 2 ], [ 'A', 3 ]]
// 各配列の2つ目の値をもとに昇順に並び替え

配列arr から重複を削除する

    arr = Array.from(new Set(arr))

配列arr の合計を出す

// 配列が全てNumber の場合
arr.reduce((prev, current) => prev + current)

ある2つの値をもとに、連続する配列を生成する

// 任意の個数の連番配列を生成する方法

[...Array(5).keys()]  //=> [0, 1, 2, 3, 4]

// 数字の1始まりで5つの配列を生成する

[...Array(5).keys()].map(i => i + 1) //=> [ 1, 2, 3, 4, 5 ]

配列に値があるかどうか確認する

const arr = [1, 2, 3];

console.log(arr.includes(2)); // true

配列に同じ文字が何個あるか計算する

// 文字列strに、Aという文字がいくつあるかを変数countに格納する
const str = 'AAaefoAapfaA'
const count = str.split('A').length - 1;
// count = 4

AからZまでの連続した配列を生成する

const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

console.log(alphabet)
//['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

配列の最大値、最小値を求める

const arr = [1,2,3]

const max = Math.max(...arr) // 3
const min = Math.min(...arr) // 1

配列をつなげて出力する

const arr = ['a', 'b', 'c'];

console.log(arr.join());
//a,b,c

console.log(arr.join(' '));
//a b c

console.log(arr.join(''));
//abc

配列に、特定の値が何個含まれているかを計算する

const arr = ['a', 'a', 'a', 'b', 'c', 'd', 'd'];
const str = 'a';
const count = arr.filter(item => item === str).length;

console.log(count); // 3

要素数が5個あり、全ての値が0である配列を生成する

const arr = Array(5).fill(0);
console.log(arr); // [0, 0, 0, 0, 0]

オブジェクトを表示する

const obj = { 1: 'a', 2: 'b' }

console.log(obj)
// {1: 'a', 2: 'b'}

Object.keys(obj).forEach(key => { console.log(key, obj[key]) })
// 1 a
// 2 b

配列内に重複する値があるかどうかをチェックする

const arr = ['A', 'B', 'C', 'D', 'A']
const arr2 = new Set(arr)

arr.length === arr2.size ? console.log('true') : console.log('false')

// 元の配列からSetオブジェクトを生成、オブジェクトの長さをsizeで計測
// 2つの値を比較し、一致すれば重複はない。異なれば元の配列に重複データがある

オブジェクトとMap オブジェクトの違い


const obj = {
    'f' : 2,
     1  : 'z',
    'c' : 4,
    'a' : '5'
}

console.log(obj)
// { '1': 'z', f: 2, c: 4, a: '5' }
// JavaScriptでは、キーに数字があるプロパティが優先して表示される

const obj2 = new Map()

obj2.set('f' , 2)
obj2.set(1 , 'z')
obj2.set('c' , 4)
obj2.set('a' , '5')

console.log(obj2)
// Map(4) { 'f' => 2, 1 => 'z', 'c' => 4, 'a' => '5' }
// Mapオブジェクトはプロパティが挿入順に表示される。

// オブジェクトとMapオブジェクトの違い
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Map

配列とオブジェクトを比較し、配列の値がオブジェクトのキーに含まれている場合バリューを表示する

const arr = ['key1', 'key2', 'key3'];
const obj = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key4', 'value4']
]);

arr.forEach(val=>{
    if(obj.has(val)){
        console.log(obj.get(val))
    }
})

Mapオブジェクトをkeyでソート

const map = new Map([
  [3, 'three'],
  [1, 'one'],
  [2, 'two'],
  [4, 'four']
]);

// 昇順
const ascendMap = new Map([...map.entries()].sort((a, b) => a[0] - b[0]));
console.log(ascendMap);
// Map(4) {size: 4, 1 => one, 2 => two, 3 => three, 4 => four}

// 降順
const descendMap = new Map([...map.entries()].sort((a, b) => b[0] - a[0]));
console.log(descendMap);
// Map(4) {size: 4, 4 => four, 3 => three, 2 => two, 1 => one}

Mapオブジェクトをvalueでソート

const map = new Map([
  ['three', 3],
  ['one', 1],
  ['two', 2],
  ['four', 4]
]);

// 昇順
const ascendMap = new Map([...map.entries()].sort((a, b) => a[1] - b[1]));
console.log(ascendMap);
// Map(4) {size: 4, one => 1, two => 2, three => 3, four => 4}

// 降順
const descendMap = new Map([...map.entries()].sort((a, b) => b[1] - a[1]));
console.log(descendMap);
// Map(4) {size: 4, four => 4, three => 3, two => 2, one => 1}

2つの文字列を比較し、ある文字列の出現回数を計算する

// 文字列line に 文字列 str が何回出現するかを計算
    const str = 'AAA'
    const line = 'AAAAAaaaAAaAAA'

// str, line の長さを算出
    const sl = str.length
    const ll = line.length

// 計算用の変数を定義    
    let result = 0
// 文字列lineの1文字目から、strと同じ長さの文字列を切り取り、strと比較
// 一致していたらカウントを一つ増やし、最後に表示する
    for(i = 0 ; i < ll; i++){
        const tmp = line.substring(i, i+sl)
        tmp === str ? result ++ : result
    }
    console.log(result)
// 4
1
0
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
1
0