Matthieu Playe
Matthieu Playe

Reputation: 3

Look into an array how many values are the same

So I trying to make a function for a slotmachine in javascript to look at 2 arrays and return a score on based on how many values are the same.

let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "c"];
let scoreCounter = 0;
let score = 0;

for (let i = 0; i < testArray.length; i++) {
  for (let y = 0; y < resultArray.length; y++) {
    if (resultArray[y] == testArray[i]) {
      scoreCounter++
    }
  }
  if (scoreCounter == 2) {
    score = 200
  } else if (scoreCounter == 3) {
    score = 300
  };
}

console.log(score)
// Return 3 times good => a,a,c are in the array.

I am trying to get this result: If the player spins the wheel and get 0 same matches he gets 0 points 2 same matches = 200 points 3 same matches = 300 points

let testArray = ["a", "b", "c"];
let resultArray = ["a", "b", "c"]; // 0 points

let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "c"]; // 200 points

let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "a"]; // 300 points

How can I fix my loops to check for this result?

Upvotes: 0

Views: 68

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386660

You could count the values and then find the count by looking to the first array.

function getScore(left, right) {
    let counts = {},
        i = 0;
     while (i < right.length) {
         counts[right[i]] = (counts[right[i]] || 0) + 1;
         i++;
     }
     return (counts[left.find(k => counts[k] > 1)] || 0) * 100;
}

console.log(getScore(["a", "b", "c"], ["a", "b", "c"]));
console.log(getScore(["a", "b", "c"], ["a", "a", "c"]));
console.log(getScore(["a", "b", "c"], ["a", "a", "a"]));

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370929

Group the array into an object whose keys are the values found, and whose values are the number of times a value has been found. Then call Math.max on the values of that object to get the maximum number of occurrences of any one element:

let resultArray = ["a", "a", "c"];

const grouped = {};
for (const item of resultArray) {
  grouped[item] = (grouped[item] || 0) + 1;
}
const maxSameVals = Math.max(...Object.values(grouped));
const score = maxSameVals === 1
  ? 0
  : maxSameVals * 100;
console.log(score);

Upvotes: 1

Related Questions