user1400915 user1400915 - 1 year ago 62
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.


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

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

Answer Source

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){
            // Got it! Rip it out:
            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:
        // ContainsIron/ ContainsSteel wasn't in there. Try removing 'Iron'/ 'Steel':


That leaves the usage as just:


Here it is as a fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download