Mercer
Mercer

Reputation: 9986

remove value from two tables

I have two table is I remove the value in both tables if in a table of the value is marked by a flag to false

this.notInModel = function (tab1, tab2) {
    for (var i = 0; i <= tab1.length - 1; i++) {
        if (!tab1[i].inModel) {
            for (var j = 0; j <= tab2.length - 1; j++) {
                if(tab1[i].name === tab2[j].name)
                    tab2.splice(j, 1);
            }
        }
    }
    for (var i = 0; i <= tab2.length - 1; i++) {
        if (!tab2[i].inModel) {
            for (var j = 0; j <= tab1.length - 1; j++) {
                if(tab2[i].name === tab1[j].name)
                    tab1.splice(j, 1);
            }
        }
    }
}

I think my curls are a bit repetitive and wanted to know if we could not refactor the code ..?

thank you.

Upvotes: 0

Views: 49

Answers (3)

friedi
friedi

Reputation: 4360

Try this:

this.notInModel = function (tab1, tab2) {
    for (var i = tab1.length; i--; ) {
        for (var j = tab2.length; j--; ) {
            if(tab1[i].name !== tab2[j].name)
                continue;

            var tab2InModel = tab2[j].inModel;

            if(!tab1[i].inModel)
                tab2.splice(j, 1);

            if(!tab2InModel)
                tab1.splice(i, 1);
        }
    }
}

The trick is to loop through both tabs in reverse order and make the checks for the name and inModel properties for every element combination.

DEMO

Upvotes: 1

Tania
Tania

Reputation: 428

The following code seems to be equivalent, though I could not test without the definition of splice or without knowing how inModel field is set.

this.notInModel = function (tab1, tab2) {
    for (var i = 1; i <= tab1.length - 1; i++) {
        for (var j = 1; j <= tab2.length - 1; j++) {
            if(!tab1[i].inModel) {
                if (tab1[i].name === tab2[j].name)
                    tab2.splice(j, 1);
            }
            if(!tab2[j].inModel) {
                if (tab1[i].name === tab2[j].name)
                    tab1.splice(i, 1);
            }
        }
    }
}

Upvotes: 0

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

You could make it more modular by creating a new function to iterate through the arrays like this:

this.notInModel = function (tab1, tab2) {
  function nim(t1,t2) {
    for (var i = 1; i <= t1.length - 1; i++) {
        if (!t1[i].inModel) {
            for (var j = 1; j <= t2.length - 1; j++) {
                if(t1[i].name === t2[j].name)
                    t2.splice(j, 1);
            }
        }
    }
  }
  nim(tab1,tab2);
  nim(tab2,tab1);
}

Upvotes: 1

Related Questions