如何比较两个数组,看看它们有多少相同的元素?

时间:2015-05-29 11:15:23

标签: javascript arrays angularjs

我有两个数组,一个是答案,第二个是correctAnswers,我需要查看答案中有多少元素与correctAnswers数组中的相同,并获得“正确”数量的“答案”百分比。我怎么做? 数组是这样的:

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

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

我不知道这是否重要,但一切都是有角度的。

5 个答案:

答案 0 :(得分:2)

很简单,你可以循环回答并检查它们。使用forEach循环,它将是:

var nbGoodAnswer = 0;
answers.forEach(function(answer, index, listAnswer){
    if(answer === correctAnswers[index]){
        nbGoodAnswer++;
    }
});

(也可以通过简单的for来完成)

然后:

console.log(nbGoodAnswer + " / " + answers.length +" bonnes réponses");
console.log((nbGoodAnswer / answers.length * 100) +"% bonnes réponses");

编辑:在另一种情况下,如果您的答案数组未订购或者可能不包含所有问题的答案:

var answer = [{question: 3, response: "C"}, {question: 1, response: "A"}];
var correctAnswer = [{question: 1, response: "A"}, {question: 2, response: "B"}, {question: 3, response: "C"}, {question: 4, response: "D"}];

var mapCorrectAnswerIdQuestion = {};
for ( var i = 0; i < correctAnswer.length; i++ ) {
    mapCorrectAnswerIdQuestion[correctAnswer[i].question] = correctAnswer[i].response;
}

// then you count
var nbGoodAnswer = 0;
for ( var j = 0; j < answer.length; j++ ) {
    if(answer[j].response === mapCorrectAnswerIdQuestion[answer[j].question]){
        nbGoodAnswer++;
    }
}

复杂程度:2N (answer.length + correctAnswer.length)

答案 1 :(得分:2)

HtmlNode

答案 2 :(得分:0)

array2 = ["Hrtkovci","Lepenica","Dec"]
array1 = ["Lepenica","Dec","Leskovac"]
var foo = [];
var i = 0;
jQuery.grep(array2, function(el) {
   if (jQuery.inArray(el, array1) == -1) foo.push(el);
   i++;
});
alert(" the difference is " + foo);

还有其他方法可以实现这一目标。

您可以看到.each jQuery循环遍历数组并根据您的选择进行比较。

但是上面的解决方案很简单,因为jQuery毕竟为我们做了这件事:D

答案 3 :(得分:0)

您可以使用angular.forEach遍历两个数组中的每个项目,并检查它们是否相等。

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);

});

编辑:对不起,没看到你想要正确答案和百分比。更新了小提琴。

Fiddle

答案 4 :(得分:-1)

试试这个

$answers =array("a"=>"Hrtkovci","b"=>"Lepenica","c"=>"Dec");

$correctAnswers =array("e"=>"Lepenica","f"=>"Dec","g"=>"Leskovac");

$result=array_intersect($answers ,$correctAnswers );

print_r($result);