0

i have this array object:

$scope.datas.labels=['10','20','30']

and also i have a function return an array object like this:

response.labels=['10','20','30','50','100','80']

i created a function which recieve the last result..but what i want is to check if a value in response.labels exists in the $scope.datas.labels i dont want to insert it..to avoid duplicated data in $scope.datas.labels, how i can do that??

i tried this but i didnt work:

$scope.concatToData=function (response) {
    if($scope.datas.labels=='') {
        $scope.datas.labels = $scope.datas.labels.concat(response.labels);
    }else {
        var i;
        for (i = 0; i < $scope.datas.labels.length; i++) {
            alert('qa' + JSON.stringify($scope.datas.labels));
            alert('res' + JSON.stringify(response.labels));
            if ($scope.datas.labels[i] !== response.labels[i]) {
                $scope.datas.labels = $scope.datas.labels.concat(response.labels[i]);
            } else {
                break;
            }
        }
    }
    $scope.datas.datasets = $scope.datas.datasets.concat(response.datasets);
}
  • Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – PMerlet Nov 08 '16 at 16:52

3 Answers3

0

You can also try that:

        var response = ['foo', 'fabio'];
        var labels = ['foo'];
        var result = response.filter((value) => {
            return labels.filter((rs) => {
                return rs == value;
            }).length == 0;
        });

It will return only the data that does not exists on $scope.datas.labels.

Fabio Silva Lima
  • 668
  • 6
  • 13
0

Take a look at the lodash library, you'll find it useful, and this will be useful for you too:

let common = _.intersection($scope.datas.labels, response.labels);
if (_.size(common) && _.includes(common, 'myValue')) { 
  // You have a winner;
  // This item (myValue) is in both;
} else {

}

Hope that helps.

rrd
  • 5,018
  • 3
  • 22
  • 32
0

Try this it will work as per your expectation and requirement.

var arr1=['10','20','30'];

var arr2=['10','20','30','50','100','80'];

for (var i in arr2) {
  if(arr2[i] != arr1[i]) {
    arr1.push(arr2[i]);
  }
}

document.getElementById('result').innerHTML = arr1;
#result {
  font-weight:bold;
  }
<div id="result"></div>
Rohit Jindal
  • 11,704
  • 11
  • 56
  • 92