user1400915 user1400915 - 9 days ago 4
jQuery Question

Manipulating array in javascript by slicing

I have an array of twelve items :

var arrToIterate = [];
arrToIterate = //Data from service to populate;


Each item in the array has two fields : Name and title.

If suppose the array has Names as :

Scenario 1:
[0]: Name: Iron
[1]: Name: Steel
[2]: Name: ContainsIron
[3]: Name: ContainsSteel
[4]: Name : Manganese
[5]: Name: Magnesium


I need the ouput as :

[0]: Name: Iron
[1]: Name: Steel
[2]: Name : Manganese
[3]: Name: Magnesium



Scenario 2:
If suppose the array has Names as :
[0]: Name: Iron
[1]: Name: Steel
[2]: Name : Manganese
[3]: Name: Magnesium
I need the output as:

[0]: Name: Manganese
[1]: Name: Magnesium


I am trying to do in this way :

$.each(arrToIterate, function (element, index, arr) {
if (element.Name == "ContainsIron" || element.Name == "ContainsSteel") {
arr.splice(index, 1);
}
});


But I am not getting the handle the second scenario . How do I achieve array manipulation for both the scenarios?

Edit :

If the array contains "ContainsIron" , then ContainsIron needs to be removed ,similarly if it contains ContainsSteel , then ContainsSteel needs to be removed.

Else

If array doesnt contain ContainsSteel , then Steel needs to be removed .

If array doesnt contain ContainsIron, then Iron needs to be removed .

Answer

Here's a simple version. First, you'll want to make a remove function which removes something if it's in there, and a function which removes a named metal:

function removeIfExists(arr,name){

    // get the index of the entry:
    for(var i in arr){
        if(arr[i].Name==name){
            // Got it! Rip it out:
            arr.splice(i,1);
            return true;
        }
    }

    // Not in the array at all.
    return false;

}

// Removes a metal from the given array
function removeMetal(arr,name){

    // Try removing e.g. ContainsIron:
    if(!removeIfExists(arr,"Contains"+name)){
        // ContainsIron/ ContainsSteel wasn't in there. Try removing 'Iron'/ 'Steel':
        removeIfExists(arr,name);
    }

}

That leaves the usage as just:

removeMetal(arrToIterate,"Iron");
removeMetal(arrToIterate,"Steel");

Here it is as a fiddle