LoginSignup
3
2

More than 5 years have passed since last update.

【JavaScript】 インデックスの配列から、多次元配列の要素を特定して変更する方法

Last updated at Posted at 2019-01-21

// 元の配列
var sanjigen = [
  [["a", "b"], ["c", "d"], ["e", "f"]],
  [["g", "h"], ["i", "j"], ["k", "l"]],
  [["m", "n"], ["o", "p"], ["q", "r"]]
];

// 変更したい要素位置の配列
const indexes = [2, 2, 1];

// 置き換える値
const replaceElement = "changed";

このような状態の時、多次元配列の要素をインデックスをまとめた配列から特定して変更する処理。


var times = 0;

function saiki(element, index) {
  // indexesで指定した要素の時
  if (times === indexes.length - 1 && index === indexes[times]) {
    return replaceElement;
  };

  if (element instanceof Array && index === indexes[times]) {
  times++;
  return element.map(saiki);
  };

   return element;
};


var changedArray = sanjigen.map(saiki)
console.log(changedArray)

出力結果

[ [ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ],
  [ [ 'g', 'h' ], [ 'i', 'j' ], [ 'k', 'l' ] ],
  [ [ 'm', 'n' ], [ 'o', 'p' ], [ 'q', 'changed' ] ] ]

やたら苦労してしまった。。。
もっといいやり方あったら教えてください。。

1/21 追記

コメントで綺麗なコードいただきました。


const
   getElement = (array, indexes) => {
      for (const index of indexes) {
         if (!Array.isArray(array) || !isFinite(index) || index < 0) {
            return undefined;
         }
         array = array[index];
      }
      return array;
   },
   setElement = (array, indexes, value) => {
      array = getElement(array, indexes.slice(0, -1));
      const index = indexes[indexes.length - 1];
      if (!Array.isArray(array) || !isFinite(index) || index < 0) {
         return value;
      }
      return (array[index] = value);
   };

参照渡しについてよくわかってなかった、、ありがとうございました!

3
2
1

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