hwe hwe - 3 years ago 201
Javascript Question

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.


<div class="ibox-content">
<table class="table table-striped">
<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 ng-repeat="issue in wiq.data">
<td><input type="checkbox" checklist-model="wiq.selections" checklist-value="issue.jira"> </td>
<td class="text-center">{{issue.description}}</td>
<td class="text-center">{{issue.jira}}</td>

<button type="button" name="button" class="btn btn-success pull-right" style="margin-top:2em;" ng-click="wiq.acknowledge()">Acknowledge</button>


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) {
ctrl.data = data;

Answer Source

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;

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

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