Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  1] [ 3]  / answers: 1 / hits: 43577  / 12 Years ago, mon, june 18, 2012, 12:00:00

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.



I am attempting to get a list of user accounts from a storage device (uses javascript and handles MOST functions ok), and compare them against a statically created list of good users.



Using a switch statement works but I really do not like it, and I'm sure there is a much better way (userList is populated dynamically from the device when I query it):



for (userName = 0; userName < userList.length; userName++) {
switch (userList[userName]) {
case 'someuser1':
printf('Username: ' + userList[userName] + ' is goodn');
break;
case 'someuser2':
printf('Username: ' + userList[userName] + ' is goodn');
break;
case 'someuser3':
printf('Username: ' + userList[userName] + ' is goodn');
break;
default:
printf('Username: ' + userList[userName] + ' is NOT goodn');
}
}


I would like to create a third array of bad users and compare them against a new array of good users, and found users. I have started with:



var goodUsers = [someuser1, someuser2, someuser3];


However I can't figure out the right combination of multiple for loops, if statements, or otherwise to compare the two and give me an array of the bad users that I can loop through and perform actions against.



Any help would be appreciated!


More From » javascript

 Answers
83

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


[#84822] Sunday, June 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
markusdamienn

Total Points: 167
Total Questions: 119
Total Answers: 93

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;