Branka Branka - 6 months ago 7
Javascript Question

How to compare two arrays to see how many same elements they have?

I have two arrays, one is answers, and second one is correctAnswers and i need to see how many elements in answers are the same as in array of correctAnswers and to get percent how many "answers" are "correct". How do i do that?
The arrays are something like this:

answers = ["Hrtkovci","Lepenica","Dec"]

correctAnswers = ["Lepenica","Dec","Leskovac"]


And i dont know if it matters but everything is with angular.

Answer

You can use angular.forEach to go through each item in both arrays and check if they are equal.

var app = angular.module('app', [])
app.controller('MyController', function ($scope) {

    $scope.answers = ["Hrtkovci", "Lepenica", "Dec"];
    $scope.correctAnswers = ["Lepenica", "Dec", "Leskovac"];

    $scope.compareArrays = function (arr1, arr2) {
        var inBoth = [];
        angular.forEach(arr1, function (a1) {
            angular.forEach(arr2, function (a2) {
                if (a1 == a2) {
                    inBoth.push(a1);
                }
            });
        });
        //return inBoth;
        var correct = 'You got ' + inBoth.length + '/' + arr2.length + ' answers!';
        var percentage = 'Correct: ' + ((inBoth.length / arr2.length) * 100).toFixed(2) + '%';
        alert(correct + '\n' + percentage);
    };

    $scope.compareArrays($scope.answers, $scope.correctAnswers);

});

Edit: Sorry, didn't see you wanted correct answers and percentage. Updated Fiddle.

Fiddle