2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのArrayをImmutableに扱うメモ

Posted at

javascriptの配列操作メソッドには、配列自身を書き換えてしまう破壊的なものが多くありますが、
メモリを気にしなければいけないケース以外は、破壊的なメソッドは使わない方がバグが減って良いです。
それらをなるべく使わないための代替手段メモ

末尾に要素を追加する

Array.pushが一般的ですが、これは破壊的です。
Array.concatかスプレッド構文を使いましょう

const newArray = baseArray.concat(valueToAdd);
const newArray2 = [...baseArray,valueToAdd];

特定のIndexの要素を書き換える

ここに関してはメソッドではありませんが。

//baseArray[targetIndex].hoge = "fuga";
const modified = baseArray.map((value,index) => {
  if(index !== targetIndex){
    return value;
  }
  return {
    ...value,
    hoge:"fuga"
  }  
})

特定の要素を削る(popやshiftなど)

Array.filterで。
Array.filterの第一引数の関数にはindexや元Arrayが引数として入るので、
そこで先頭や末尾判定が出来ます。

const shifted = baseArray.filter((value,index) => index !== 0);
const popped = baseArray.filter((value,index,array) => index != array.length -1);

要素を増減させる(splice)

減らすだけならfilterで行けますがSpliceではないといけない操作をする場合はreduceが必要です。
大体再現しようとすると以下のような感じ?

//array.splice(startIndex,deleteCount,items)
const spliced = baseArray.reduce((prev,current,index) => {
  if(index < startIndex || index > startIndex + deleteCount){
    return prev.concat(current);
  }
  if(index === startIndex){
    deleteCount <== 0 ? prev.concat(items).concat(current):prev.concat(items);
  }
  return prev;
},[]);

ただ、Spliceの機能のすべてを使うわけではないのならもっとシンプルでいいし、
厳密にImmutableにこだわらないのなら、以下のようにspread演算子で配列をコピーしてからspliceした方が無難。
この記事の項目全てに当てはまってしまいますが。

const spliced = [...baseArray];
spliced.splice(startIndex,deleteCount,items);

配列の反転(reverse)

reduceRightを使うと逆順に回るので+concatで。

const reversed = baseArray.reduceRight((prev,current) => prev.concat(current),[]);

配列のsort

こればかりはちょっといい方法が思いつかなかったので、配列をコピーしてソートする方向で。

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?