hwe
hwe

Reputation: 227

for loop not returning data when iterating through multiple values

I have a function which its job its to delete a value selected by the user, it loops through an array of selected values and the data, when it iterates through both it checks if the selected value is equal to any property in the data, if it returns true, I get a new array of data.

When I select one value in the checkbox I do indeed see the correct data being returned, but when I select multiple my function does not work. I have being pondering all day, I will really appreciate any input.

HTML

<div class="ibox-content">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Select</th>
                <th class="col-xs-3">Issue Description</th>
                <th class="col-xs-3 text-center">Category</th>
                <th class="col-xs-3 text-center">Jira</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="issue in wiq.data">
                <td><input type="checkbox" checklist-model="wiq.selections" checklist-value="issue.jira"> </td>
                <td>{{issue.issue}}</td>
                <td class="text-center">{{issue.description}}</td>
                <td class="text-center">{{issue.jira}}</td>
            </tr>

            <pre>{{wiq.selections}}</pre>
        </tbody>
    </table>
    <form>
        <button type="button" name="button" class="btn btn-success pull-right" style="margin-top:2em;" ng-click="wiq.acknowledge()">Acknowledge</button>
    </form>
</div>

Controller.js

ctrl.selections = []
ctrl.data = [
    {issue:"CMDY has issue", description:"issue",jira:"CDVR-173"},
    {issue:"SPK has issue", description:"issue",jira:"CDVR-125"}
]

ctrl.acknowledge = function() {
    var data = [];
    for (var i = 0; i < ctrl.data.length; i++) {
        for (var j = 0; j < ctrl.selections.length; j++) {
            if (ctrl.selections[j] != ctrl.data[i].jira) {
                data.push(ctrl.data[i]);
            }
        }
    }
    ctrl.data = data;
    console.log(ctrl.data)
};

Upvotes: 1

Views: 53

Answers (2)

pegla
pegla

Reputation: 1866

Simple one liner will solve your problems, try this:

ctrl.acknowledge = function() {
    var data = ctrl.data.filter(val => ctrl.selections.indexOf(val.jira) === -1);
    ctrl.data = data;
    console.log(ctrl.data)
  };

Here's jsfiddle: http://jsfiddle.net/pegla/xj9gqqxn/7/

Upvotes: 0

Renaud T.
Renaud T.

Reputation: 139

When you have multiple selection, you loop multiple times, so you call "push" too many times.

try :

function filterData(somedata, selections) {
    return somedata.filter(item => (selections.findIndex(o => o === item.jira ) == -1));
};

then

ctrl.acknowledge = function() {
    ctrl.data = filterData(ctrl.data,ctrl.selections);
    console.log(ctrl.data)
};

Upvotes: 1

Related Questions