简体   繁体   中英

Return match between two array values in AngularJS

Am having a problem to return match array between two array element, please any help is important here is my code

      $scope.MacA = [
  {
    name: '24:fd:52:c3:d8:35',
    sector: 'A23'
  }, 

  {
    name: '56:db:30:4b:57:45',
    sector: 'It support'
  },
  {
    name: 'b6:b6:76:6b:e9:00',
    sector: 'A24'
  },
  {
    name: 'e8:74:e6:a1:14:16',
    sector: 'Vodafone Guest'
  },
  {
    name: 'dc:4a:3e:b7:32:0e',
    sector: 'Direct HP officejet'
  }
  ,
  {
    name: '7c:4c:a5:32:13:29',
    sector: 'skyb7'
  }

] and array 2 is

scope.match = ['dc:4a:3e:b7:32:0e','7c:4c:a5:32:13:29' ];

and here is the function that returns the match if found

 $scope.getList = function(){
      // $scope.wifiList = WifiService.list();
      var c = $scope.MacA;
      var m = WifiService.list();
      for(var i = 0;i < c.length;i++) {
        for(var j = i;j < m.length;j++) { // Notice the j = i;
          if (c[i].name === m[j]) {
            $scope.result = c[i].sector;
        // $scope.result = 'Its working';
        break;
          } else {
             $scope.result = "Sorry!";
          }
        };
      };
  return $scope.result;
}

You didn't specify what exactly you want as the result, but here is a possible version that looks for matches.

var result = [];
match.forEach(m => result.push(MacA.find(macA => macA.name === m)));
   MacA = [
  {
    name: '24:fd:52:c3:d8:35',
    sector: 'A23'
  }, 

  {
    name: '56:db:30:4b:57:45',
    sector: 'It support'
  },
  {
    name: 'b6:b6:76:6b:e9:00',
    sector: 'A24'
  },
  {
    name: 'e8:74:e6:a1:14:16',
    sector: 'Vodafone Guest'
  },
  {
    name: 'dc:4a:3e:b7:32:0e',
    sector: 'Direct HP officejet'
  },
  {
    name: '7c:4c:a5:32:13:29',
    sector: 'skyb7'
  }
]

Match = ['dc:4a:3e:b7:32:0e','7c:4c:a5:32:13:29' ];

MacA.filter(({name}) => Match.includes(name)).map(({sector}) => sector)
// RETURNS // ["Direct HP officejet", "skyb7"]

SO, given your code above, something like this:

 $scope.getList = function(){
   return $scope.result = $scope.MacA.filter(({name}) => $scope.match.includes(name)).map(({sector}) => sector)
}

I've refactored some of your code.

 $scope.getList = function(){
  var devices = $scope.MacA;
  var macList = WifiService.list();
  var results = devices.reduce((acc, device) => acc.concat(macList.find(current.name)? [current.sector]:[]), []);
  return results.length? $scope.results = results : $scope.results = 'Sorry!';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM