Wiki_JS_Array - inoueshinichi/Wiki_Web GitHub Wiki

JS 配列操作の基本

配列の生成

  • let list1 = ['あ','い','う'] // 配列リテラル
  • let list2 = new Array('あ','い','う') // new演算子
// 長さ10の空の配列を生成
let list3 = new Array(10);

// 密配列と疎配列
const sparseArray = [1, , 3];
console.log(sparseArray.length); // 3
console.log(sparseArray[1]); // undefined

// 2次元配列
const matrix = [
  [ 'a', 'b' ],
  [ 'c', 'd' ]
];
console.log(matrix[0][0]); // 'a'

配列の削除

let list = ['い','の','う','え'];
list.length = 0; // 要素全削除になる. list = []

配列のコピー

// スプレッド構文
const list1 = ['a','b','c'];
const list2 = [...list1];

// sliceメソッド
const list3 = ['d','e','f'];
const list4 = list3.slice();

// concatメソッド
const list5 = ['g','h','i'];
const list6 = list5.concat();

// Array.fromメソッド
const list7 = ['j','k','l'];
const list8 = Array.from(list7);

プロパティ/メソッド名

プロパティ/メソッド名 内容
array.unshift(elem) 先頭に要素を挿入
array.push(elem) 末尾に要素を挿入
array.shift() 先頭から要素を抽出
array.pop() 末尾から要素を抽出
array.splice(start [, count [, items]]) 複数要素を追加/置換/削除
array.slice([start [, end]) 特定範囲の要素をコピーして取得
array.indexOf(searchElem [, fromIndex]) 要素を先頭から検索
array.lastIndexOf(searchElem [, fromIndex]) 要素を末尾から検索
array.findIndex((value, index, array) => {...} [, thisArgs]) 任意の条件式によって配列を検索する(Indexを取得)
array.find((value, index, array) => {...} [, thisArgs]) 任意の条件式によって配列を検索する(オブジェクトを取得)
array.findLast((value, index, array) => {...} [, thisArgs]) 要素を末尾から検索(オブジェクトを取得)
array.includes(searchElem, [, fromIndex]) 要素の存在チェック
array.join([separator]) 区切り文字(',')@デフォルトで配列を文字列として連結.
array.flat([depth]) 入れ子配列をフラット化(デフォルトはdepth=1, 全展開はdepth=Infinity)
array.copyWithin(target [, start [, end]]) 配列内の要素を移動する(コピーになる)
array.fill(elem, start [, end]) 配列内の要素を同一値で満たす
array.concat(array) 配列を連結する
array.reverse() 配列のならびを逆にする
array.sort((m,n) => {... return [m] - [n] }) 降順ソート: 戻り値が負数のとき交換, 昇順ソート: 戻り値が正数のとき交換)
array.sort() 配列を辞書順に並べる
array.forEach((value, index, array) => {...} [, thisArgs]) 配列の内容を順に処理する
array.map((value, index, array) => {...} [, thisArgs]) 配列の内容を指定したルールで加工する
array.flatMap((value, index, array) => {...} [, thisArgs]) Mapで加工してFlatで平坦化して出力する
array.some((value, index, array) => {...} [, thisArgs]) 条件式に合致する要素が存在するか判定(any)
array.every((value, index, array) => {...} [, thisArgs]) 条件式に合致する要素が存在するか判定(all)
array.filter((value, index, array) => {...} [, thisArgs]) 配列から条件に合致した要素だけを取得する
array.reduce((result, value, index, array) { ... }, initial) 配列内の要素を順に処理して1つにまとめる(左から)
array.reduceRight((result, value, index, array) { ... }, initial) 配列内の要素を順に処理して1つにまとめる(右から)
array.with(index, element) 配列を複製して指定した要素を変更して返す
array.at(-1) 末尾インデックスを取得

クラスメソッド一覧

操作 コマンド
配列ライクなオブジェクトを配列化する(配列コピーに使える. ただし浅いコピー) Array.from(obj [, mapFn [, thisArg]])
配列判定 Array.isArray(array)

メソッドの利用例

[ES2022] Array.prototype.at

  • Pythonのインデクシングと同じことができる
const array = ['a', 'b', 'c'];

console.log(array.at(0)); // 'a'
console.log(array.at(1)); // 'b'
console.log(array.at(-1)); // 'c'
console.log(array[array.length - 1]); // 'c'
console.log(array[-1]); // undefined

配列オブジェクトの判定

  • Array.isArray()メソッドを使う
const obj = {};
const array = [];

console.log(Array.isArray(obj)); // false
console.log(Array.isArray(array)); // true

// typeof演算子では, 配列はオブジェクトと判定されるため, 使えない.
console.log(typeof array); // "object"

[ES2015] TypedArray

  • 固定長
  • 型付き
  • 用途は, バイナリデータのバッファ
const typedArray = new Int8Array(8);
console.log(Array.isArray(typedArray)); // false

undefinedの要素と未定義の要素の違い

  • 疎配列で, 該当するインデックスがない場合, undefinedを返す
  • 一方で, 密配列でundefinedを値とする配列はundefinedを返す
  • 疎配列と密配列のundefined値を判別することができない.
  • Object.hasOwn()静的メソッドで解決できる.
const denseArray = [1, undefined, 3];
const sparseArray = [1, , 3];
console.log(denseArray[1]); // undefined
console.log(sparseArray[1]); // undefined

// Object.hasOwn()メソッド
console.log(Object.hasOwn(denseArray, 1)); // true
console.log(Object.hasOwn(sparseArray, 1)); // false
// true/falseを制御して処理する

配列から要素を検索

  • indexOf()
  • lastIndexOf()[ES2023]
  • indexOf()/lastIndexOf()メソッドは, プロパティ値が同じでも異なるインスタンスであれば, 異なるものと判別される.
  • findIndex()
  • find() [ES2015]
  • findLast() [ES2023]
const obj = { key: "value" };
const array = ["A", "B", obj];
console.log(array.indexOf({key: "value"}); // arrayの`obj`と引数の`obj`は異なるインスタンス  => -1

console.log(obj === { key: 'value' }); // false

// 同じインスタンス`obj`で検索すれば問題ない
console.log(array.indexOf(obj)); // 2
  • 異なるインスタンスでプロパティ値が同一のものを検索するにはfindIndex()メソッドを使用する
const colors = [
  {"color": "red"},
  {"color": "green"},
  {"color": "blue"}
];

const indexOfBlue = colors.findIndex((obj) => {
  return obj.color === "blue";
});

console.log(indexOfBlue); // 2
console.log(colors[indexOfBlue]); // {"color": "blue"}

const blueColor = colors.find((obj) => {
  return obj.color === "blue";
});

console.log(blueColor); // {"color": "blue"}

const whiteColor = colors.find((obj) => {
  return obj.color === "white";
});

console.log(whiteColor); // undefined
  • findLastIndex(), findLast()の利用
const records = {
  { date: "2020/12/1", count: 5 },
  { date: "2020/12/2", count: 11 },
  { date: "2020/12/3", count: 9 },
  { date: "2020/12/4", count: 12 },
  { date: "2020/12/5", count: 3 }
];

const lastRecordIndex = records.findLastIndex((record) => {
  return record.count > 10;
});

const firstRecordIndex = records.findIndex((record) => {
  return record.count > 10;
});

console.log(firstRecordIndex); // 1
console.log(records[firstRecordIndex]); //  { date: "2020/12/2", count: 11 }
console.log(lastRecordIndex); // 3
console.log(records[lastRecordIndex:); // { date: "2020/12/4", count: 12 }

const lastRecord = records.findLast((record) => {
  return record.count > 10;
});

console.log(lastRecord); // { date: "2020/12/4", count: 12 }

sortによる数値順で並べる

  • 戻り値 < 0のとき、要素が交換となる.
  • 降順ソート: return m - n;と指定する。
  • 昇順ソート: return n - m;と指定する。
let list = [5,25,10];

// 降順ソート
list.sort((m, n) => {
  return m - n;
}); // [5,10,25]

// 昇順ソート
list.sort((m, n) => {
  return n - m;
}); // [25,10,5]

flatMapメソッド

let list = [1,2,3,4,5];
list.flatMap(function(value) {
  return [value*2, value**2];
}); // [2,1,4,4,6,9,8,16,10,25]

reduceメソッド

let list = [4,2,8,3];
list.reduce(function(result, value) {
  return result * value;
}); // 4*2=8, 8*8=64, 64*3=192