I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

Getting undefined error while processing array

I have 2 arrays like below:

$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]
$scope.selected = [{ val:12} , { val:13} ] //based on checkbox  selection

Now i just want to add selected value to Statistics array and remove those which doesnt exist in selected but ignoring 1st record of statistics.

Expected output

$scope.Stat.Statistics ={[ val:10]} , {[ val:12]} , {[ val:13]}

Code:

for (var i = 0; i < selected.length; i++) {
    for (var j = 1; j <= $scope.Stat.Statistics.length; j++) {
        //ignore 1st record for comparision
        if (selected[i].val != $scope.Stat.Statistics[j].val) {
            $scope.Stat.Statistics.splice(j, 1);
            $scope.Stat.Statistics[j].push(selected[i]);
        }
    }
}

Update:In case of same value in Statistics and selected i would like to keep statistics value.

Error:$scope.Stat.Statistics[j] is undefined

Upvotes: 1

Views: 77

Answers (2)

nikjohn
nikjohn

Reputation: 21852

$scope.Stat.Statistics ={[ val:10]} , {[ val:11]} , {[ val:13]} ,{[ val:14]}

This is not valid Javascript. If you want an array, you should be defining it like:

$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]

var Statistics = [{
  val: 10
}, {
  val: 11
}, {
  val: 13
}, {
  val: 14
}];

var selected = [{
  val: 12
}, {
  val: 13
}];

var found = selected;
Statistics.map(function(statistic) {
  selected.map(function(selectedItem) {
    if(selectedItem.val === statistic.val) {
      found.push(selectedItem); 
    }
  });
});

console.log(found);

Of course, I've factored out the Angular element out of it, but this same logic should work.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could take the first element of $scope.Stat.Statistics, you want to keep and concat $scope.selected to the first element.

var $scope = { Stat: {} };

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];
$scope.Stat.Statistics = [$scope.Stat.Statistics[0]].concat($scope.selected);

console.log($scope.Stat.Statistics);

Edit: keeping common items with same val and append the rest to the array.

var $scope = { Stat: {} },
    hash = {},
    i;

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13, extra: 42 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];

$scope.selected.forEach(function (a) {
    hash[a.val] = a;
});

i = $scope.Stat.Statistics.length;
while (i--) {
    if (hash[$scope.Stat.Statistics[i].val]) {
        delete hash[$scope.Stat.Statistics[i].val];
        continue;
    }
    if (i === 0) {
        continue;
    }
    $scope.Stat.Statistics.splice(i, 1);
}
Object.keys(hash).forEach(function (k) {
    $scope.Stat.Statistics.push(hash[k]);
});

console.log($scope.Stat.Statistics);

Upvotes: 1

Related Questions