Javascript compare items in one array

后端 未结 5 1595
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 00:10

Pardon my complete lack of javascript knowledge in advance, but I can\'t seem to find a good example of how to compare two arrays and create another array based the results.

相关标签:
5条回答
  • 2021-01-27 00:18

    Use indexOf to find if the user exists in your array.

    var goodUsers = ["someuser1", "someuser2", "someuser3"];
    var storedUsers = ["someuser1", "user", "user3"];
    for(var goodUser in goodUsers){
        if(storedUsers.indexOf(goodUsers[goodUser])>-1){
           console.log('User:' + goodUsers[goodUser] + ' is good.')
           }
    }
        ​
    
    0 讨论(0)
  • 2021-01-27 00:21

    Array's indexOf method is sweet. It returns the position of an element in the array, if it exists, or returns -1 if it does not.

    var goodUsers = ["someuser1", "someuser2", "someuser3"];
    var users = ["someuser1", 'basuser'];
    var user;
    
    for (var i=0; i < users.length; i++) {
      user = users[i];
      if (goodUsers.indexOf(user) >= 0) {
        console.log(user + ' is a good user');
      } else {
        console.log(user + ' is BAD!!!');
      }
    }​
    

    http://jsfiddle.net/qz5fx/1

    0 讨论(0)
  • 2021-01-27 00:37

    The brute force method would be something like this:

    var users = []; // here is where you get the users from the device
    var goodUsers = []; // here you get your good users list
    var badUsers = []; // initialize an empty array for bad users
    
    for (var i=0; i< users.length; i++) {
        var isAGoodUser = false;
        for(var y=0; y< goodUsers.length; y++) {
            if(users[i] == goodUsers[y]) {
                printf('Username: ' + users[i] + ' is good\n');
                isAGoodUser = true;
                break;
            }
        }
        if(!isAGoodUser){
            printf('Username: ' + users[i] + ' is NOT good\n');
            badUsers.push(users[i]);
        }
    }
    
    0 讨论(0)
  • 2021-01-27 00:41

    I like the indexOf method for this. Example fiddle: http://jsfiddle.net/8MV3J/

    var good = ["someuser1", "someuser2", "someuser3"];
    var bad = [];
    var ugly = ["someuser4", "someuser1", "someuser5", "someuser2", "someuser6", "someuser3", "someuser7"];
    var i = 0;
    var li;
    
    for (i = 0; i < ugly.length; i += 1) {
        if (good.indexOf(ugly[i]) === -1) {
            bad.push(ugly[i]);
        }
    }
    
    for (i = 0; i < bad.length; i += 1) {
        li = $('<li />').text(bad[i]);
        $('ul#bad').append(li);
    }​
    
    0 讨论(0)
  • 2021-01-27 00:42

    For larger lists, a more efficient way than .indexOf is to put your good user list into an object and use direct lookup on that object. This also works in older browsers as it doesn't require the Array.indexOf() method.

    var goodUsers = {
        "someuser1": true, 
        "someuser2": true, 
        "someuser3": true
    };
    

    Then, you can check to see if a user is in that list with:

    if (goodUsers[user])
    

    For longer lists, this is a lot more efficient than using indexOf which just iterates through the array comparing each item in the array to your target because this uses a hash lookup (like a hash table).

    If you had a candidate set of users and you wanted to know which ones were in the goodUsers list, you could do that like this:

    var goodUsers = {
        "someuser1": true, 
        "someuser2": true, 
        "someuser3": true
    };
    
    var candidateUsers = ["someuser4", "someuser1", "someuser5", "someuser2", "someuser6", "someuser3", "someuser7"];
    
    function checkUsers(candidates) {
        var goods = [];
        for (var i = 0, len = candidates.length; i < len; i++) {
            var item = candidates[i];
            if (goodUsers[item]) {
                goods.push(item);
            }
        }
        return(goods);
    }
    
    var validUsers = checkUsers(candidateUsers);
    

    Edit:

    While this object lookup still works in modern Javascript, there is now a Set and Map object in ES6 that can do this cleaner and more efficiently. For the user lookup, you would probably use the Set object.

    const goodUsers = new Set(["someUser1", "someUser2", "someUser3"]);
    goodUsers.add("someUser4");
    
    if (goodUsers.has(user)) {
        // user is in the set
    }
    
    0 讨论(0)
提交回复
热议问题