Javascript compare items in one array

后端 未结 5 1651
被撕碎了的回忆
被撕碎了的回忆 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: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
    }
    

提交回复
热议问题