Reputation: 91
I want to determine how many of the items in these two arrays match, then store that in state as a number.
For example
const [score, setScore] = React.useState(0)
const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2
I tried
function checkSelectedAnswer(selections, allCorrectAnswers) {
selections.map(eachChoice =>
eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer)
? setScore(prevScore => prevScore + 1) : 0
)
}
Please explain why my code isn't working as well if you can.
Upvotes: 3
Views: 4090
Reputation: 3662
First of all, I would suggest to use a Set to avoid duplicate values and then an intersection to see what element matches.
const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
const intersection = new Set([...a].filter(x => b.has(x)));
// {2,3}
Using Set, you will also improve performance since there is no duplicate values.
Here is a small benchmark
Checked test: Javascript Set intersection x 70,358 ops/sec ±2.26% (61 runs sampled)
Checked test: Javascript Array intersection x 40,687 ops/sec ±1.22% (67 runs sampled)
Success! Validation completed.
Your code does not work since you comparing the answer (a string) with an array of item which end up to be always false.
Upvotes: 0
Reputation: 20304
You can use filter
method and its second parameter that is index
. After you filter for all elements that match in two arrays, you can just return the length
property witch will present the number of matches.
const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const checkSelectedAnswer = (selections, allCorrectAnswers) => selections.filter((eachChoice,index) => eachChoice === allCorrectAnswers[index]).length;
const numberOfCorrectAnswers = checkSelectedAnswer(selections, allCorrectAnswers);
console.log(numberOfCorrectAnswers);
Upvotes: -1
Reputation: 370679
.map
(either at the top level or the nested one) doesn't make sense, because you aren't trying to transform each element of one array into another. If you want to use an array method, use .reduce
instead, and use the index in the callback to access the associated element in the other array to see if it's equal.
const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const totalCorrect = selections.reduce(
(correctSoFar, answer, i) => correctSoFar + (answer === allCorrectAnswers[i]),
0
);
console.log(totalCorrect);
// setScore(totalCorrect);
or do
const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
let totalCorrect = 0;
selections.forEach((answer, i) => {
if (answer === allCorrectAnswers[i]) {
totalCorrect++;
}
});
console.log(totalCorrect);
// setScore(totalCorrect);
Upvotes: 2