• @user94507, this should work too - notice the switching of inner w/ outer loop.

    // findFirstInArrWForEach.js
    // @user94507 - 20181002
    
    function findFirstIn(arr,matcher) { 
      var r; arr.forEach(function(elt){ 
        if (!r && matcher(elt)) r = elt; });
      return r; }
    
    function findMyAp(aAp,aMyAp) {
      var myAp;
      findFirstIn(aAp,function(elt){
        myAp = myAp || findFirstIn(aMyAp,function(elt2){
          return elt.ssid == elt2.ssid; });
        return myAp; });
      return myAp; }
    
    var oWifi = require('Wifi'), myAp;
     
    oWifi.scan(function(aAp) {
        aAp.sort(function(a,b){return a.rssi===b.rssi?0:(a.rssi<b.rssi?1:-1);}­);
        if ((myAp = findMyAp(aAp,aMyAp))) {
          oWifi.connect(myAp.ssid, {password: myAp.pwd}, function(err) {
              if (err===null) {
                console.log('Connection success to:', myAp.ssid);
              } else {
                console.log('Connect error: ',err);
              }
            });
        } else {
          console.log('no Ap found');
        }
      });
    

    It still loops through all elements of the outer array (aMyAP[]), but stops comparing and looping through though the inner array (aAP[]) on first find (match).

    Both the matcher() functions return true, but truthy is enough, and therefore it would be sufficient to just return my2 ;

    If you do not like the looping through the first one and have even the optional telling where to start looping including handling of undefined and null arrays, you can use this findFirstIn(arr,mchr,strt) function (It was part of my survival kit w/ JS 1.2,..):

    findFirstIn(arr, mchr, strt, endx):

    • arr is the array to search in
    • mchr function taking array element as argument and return true on match, else false
    • strt is optional search start index, defaults to 0 when ommitted
    • endx is optional search end index exclusive, defaults to arr.length

    returns first element for which 'mchr(element)' return true, else undefined
    Note: does not help to find 'undefined' elements in array ;-)

    function findFirstIn(arr,mchr,strt,endx) {
      var i = ((strt) ? strt : 0)-1, m = ((arr) ? (endx) ? endx : arr.length : 0)-1;
      while (i<m) if (mchr(arr[++i])) return arr[i]; return undefined; }
    
About

Avatar for allObjects @allObjects started