配列から特定のアイテムを削除するJavaScriptプログラム

Javascript

例1:Forループの使用

// program to remove item from an array

function removeItemFromArray(array, n) {
    const newArray = [];

    for ( let i = 0; i < array.length; i++) {
        if(array[i] !== n) {
            newArray.push(array[i]);
        }
    }
    return newArray;
}

const result = removeItemFromArray([1, 2, 3 , 4 , 5], 2);

console.log(result);

出力

[1, 3, 4, 5]

上記のプログラムでは、アイテムはを使用して配列から削除されます for ループ。

ここに、

  • ザ・ for loopは、配列のすべての要素をループするために使用されます。
  • 配列の要素を反復処理しているときに、削除する項目が配列要素と一致しない場合、その要素はにプッシュされます。 newArray
  • ザ・ push() メソッドは要素をに追加します newArray

例2:Array.splice()の使用

// program to remove item from an array

function removeItemFromArray(array, n) {
    const index = array.indexOf(n);

    // if the element is in the array, remove it
    if(index > -1) {

        // remove item
        array.splice(index, 1);
    }
    return array;
}

const result = removeItemFromArray([1, 2, 3 , 4, 5], 2);

console.log(result);

出力

[1, 3, 4, 5]

上記のプログラムでは、削除する配列と要素がカスタムに渡されます removeItemFromArray() 関数。

ここに、

const index = array.indexOf(2);
console.log(index); // 1
  • ザ・ indexOf() メソッドは、指定された要素のインデックスを返します。
  • 要素が配列にない場合、 indexOf() 戻り値 -1
  • ザ・ if 条件は、削除する要素が配列にあるかどうかをチェックします。
  • ザ・ splice() メソッドは、配列から要素を削除するために使用されます。

注意:上記のプログラムは、重複する要素のない配列に対してのみ機能します。

一致する配列の最初の要素のみが削除されます。

例えば、

[1, 2, 3, 2, 5] 結果は [1, 3, 2, 5]



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です