Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách so sánh hai mảng xem có bao nhiêu phần tử giống nhau JavaScript

Cho hai mảng: đáp án đúng và đáp án thí sinh (đã bị xáo trộn thứ tự). Không có 2 câu cùng đáp án. Viết hàm tìm các phần tử chung và tính phần trăm điểm.

Ví dụ

const correct = ['India', 'Japan', 56, 'Mount Everest', 'Nile', 'Neil Armstrong', 'Inception', 'Lionel Messi', 'Joe Biden', 'Vatican City'];const answered = ['Nile', 'Neil Armstrong', 'Joe Biden', 'Mount Everest', 'Vatican City', 'Inception', 'Japan', 56, 'China', 'Cristiano Ronaldo'];const findPercentage = (first, second) => {  const count = first.reduce((acc, val) => {    if (second.includes(val)) return ++acc;    return acc;  }, 0);  return (count / first.length) * 100;};console.log(`Candidate have scored ${findPercentage(correct, answered)}%`);

Kết quả

Đầu ra trong console sẽ là:

Candidate have scored 80%