どうも、ちょげ(@chogetarou)です。
配列(array)の特定の要素を置換する方法を紹介します。
方法

配列(array)の特定の要素を置換する方法は、3つあります。
indexOf()
1つ目は、indexOf()を使う方法です。
まず、配列からindexOf()を呼び出します。
indexOf()の引数の置換する要素を指定します。
そして、[]を使い、配列のindexOf()の結果のインデックスの要素に新しい値を代入します。
//arr=対象の配列, item=置換する要素, newValue=要素の新しい値
const index = arr.indexOf(item);
arr[index] = newValue;
上記の代入は、配列(array)の特定の要素を置換します。
使用例
const nums = [1, 2, 3, 4, 5];
const index = nums.indexOf(3);
nums[index] = 10;
console.log(nums);
出力:
[LOG]: [1, 2, 10, 4, 5]
map()
2つ目は、map()を使う方法です。
まず、配列からmap()を呼び出します。
map()の引数に、1つの引数を持つ関数を指定します。
関数の処理で、引数が特定の要素と等しいかで条件分岐します。
そして、引数が特定の要素と等しいときは置換後の新しい値、異なる場合は引数を返します。
//arr=対象の配列, value=置換する要素の値, newValue=要素の新しい値
const result = arr.map((item) => item === value ? newValue : item)
//if文を使う場合
const result = arr.map(function(item) {
if (item === value) {
return newValue
}
return item;
});
上記のmap()は、配列(array)の特定の要素を全て置換した結果を返します。
使用例
const nums = [1, 1, 2, 1, 2, 1, 3, 3, 4, 5];
const result = nums.map((item) => item === 1 ? 0 : item)
console.log(result)
出力:
[0, 0, 2, 0, 2, 0, 3, 3, 4, 5]
ループ
3つ目は、ループを使う方法です。
まず、for…in文で配列のインデックスをループします。
次に、ループ処理で、if文を使い配列のインデックスの要素と特定の要素が等しい時を条件に条件分岐します。
条件でtrueを返した時に、配列のインデックスに新しい値を代入します。
//arr=対象の配列, item=置換する要素, value=置換後の値
for (const index in arr) {
if (arr[index] === item) {
arr[index] = value; //新しい値を代入
}
}
上記のループは、配列(array)の特定の要素を全て置換します。
使用例
let nums = [1, 1, 2, 1, 2, 1, 3, 3, 4, 5];
for (const index in nums) {
if (nums[index] === 1) {
nums[index] = 0;
}
}
console.log(nums)
出力:
[0, 0, 2, 0, 2, 0, 3, 3, 4, 5]
まとめ
配列(array)の特定の要素を置換する方法は、次の3つです。
- concat()を使う方法
const index = arr.indexOf(item);
arr[index] = newValue;
- map()を使う方法
const result = arr.map((item) => item === value ? newValue : item)
- ループを使う方法
for (const index in arr) { if (arr[index] === item) { arr[index] = value; } }
コメント