简体   繁体   中英

Compare 2 items in a javascript or jquery

I will be glad if I can get help with this issue.

I created a set of questions with options for users and the computer to select from using jquery. The selections of the user and that of the computer are stored in 2 different arrays like the one shown below: userSelection = ["a","b","c","a","d"]; computerSelection = ["e","b","a","d","d"];

Now I want to count the items that matched in both selections eg items 2 & 5 ("b" and "d") in the example shown above, how can I go about it? I have tried using the "==" and "===" signs to compare but I couldn't solve this. I really will appreciate if I can be pointed in the right direction. I don't mind if the answer is in jquery or javascript. Thanks

The simplest solution is to iterate over one array and see if a value at the same index in the other array is the same - if yes, increment the counter:

 const userSelection = ["a","b","c","a","d"]; const computerSelection = ["e","b","a","d","d"]; let count = 0; userSelection.forEach(function (answer, i) { if (computerSelection[i] === answer) { count++; } }); console.log(count);

You can use a reduce to check each item and then increase the counter

 const userSelection = ["a","b","c","a","d"]; const computerSelection = ["e","b","a","d","d"]; const count = userSelection.reduce((counter, item, index) => item === computerSelection[index] ? ++counter : counter, 0); console.log(count);

If the order doesn't matter:

 const userSelection = ["a","b","c","a","d"]; const computerSelection = ["e","b","a","d","d"]; const count = userSelection.reduce((counter, item, index) => computerSelection.includes(item) ? ++counter : counter, 0); console.log(count);

=== and == will check if the two object are the same, ans most of the time it can be read as 'are they the same object in memory':

 x = [1,2]; y = [1,2]; console.log(x==y); // false console.log(x===y); // false console.log(x===x); // true

what you can do is create a function that define the equality condition for the two objects: in case of array, if the elements match (and in your use case, the order matters):

 userSelection = ["a","b","c","a","d"]; computerSelection = ["e","b","a","d","d"]; function checkSelections(user, computer){ return computer.filter(function(item, i){ return user[i] === item; }); } console.log(checkSelections(userSelection, computerSelection));

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