比较两个数组并推入另一个数组错误的位置元素

时间:2014-05-05 10:06:51

标签: javascript jquery arrays

我有两个数组,都是字符串:

var correctAnswers = ["0", "1", "2", "3", "4", "5"];

和第二:

var finalArray = ["0", "1", "4", "3", "5", "2"];

我想比较它们,如果不匹配第二个,则首先提取元素并将它们推送到另一个数组中,如下所示:

finalArray = ["0", "1", "3"];

var toChange = ["4", "5", "2"];

4 个答案:

答案 0 :(得分:1)

var toChange = [];
for (var i = finalArray.length - 1; i >= 0; i--) {
    if (finalArray[i] !== correctAnswers[i]) {
        toChange.push(finalArray[i]);
        finalArray.splice(i, 1);
    }
}

关键是将 down 从长度迭代到0,而不是像往常一样从0到长度。这是因为splice在删除元素后更改了所有元素的索引,因此正常迭代会在每次拼接后跳过一个元素。

答案 1 :(得分:1)

这样做:

http://jsfiddle.net/XiozZe/NkM6s/

var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var finalArray = ["0", "1", "4", "3", "5", "2"];
var correctFinal = [];
var toChange = [];

for(var i = 0; i < correctAnswers.length; i++){
    if(correctAnswers[i] === finalArray[i]){
        correctFinal[correctFinal.length] = finalArray[i];
    }
    else{
       toChange[toChange.length] = finalArray[i];
    }   
}

答案 2 :(得分:1)

您也可以使用jQuery map方法:

var toChange = $.map(finalArray, function(v, k){
    return correctAnswers[k] !== v ? v: null;
});

finalArray = $.map(finalArray, function(v, k){
    return correctAnswers[k] === v ? v: null;
});

DEMO

或使用array.prototype.filter()

var toChange = finalArray.filter(function(v, k){
    return correctAnswers[k] !== v;
});

finalArray = finalArray.filter(function(v, k){
    return correctAnswers[k] === v;
});

filter DEMO

答案 3 :(得分:1)

首先,您必须定义变量

// Define your variables
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var answers     =    ["0", "1", "4", "3", "5", "2"];
var finalArray = [];
var toChange = [];

然后创建一个循环,循环遍历Answers数组。

// comparing them could be done with a simple loop
for (var i = 0; i<answers.length; i++) {
    if (correctAnswers[i] == answers[i]) { //if they're equal, push the value into the final array
        finalArray.push(answers[i]);
    } else { // if not, push them into the toChange array
        toChange.push(answers[i]);
    }
}

这会给你改变= [0,1,3] 如果你想改变= [0,1],你必须把它改成

toChange = answers.slice(0);

for (var i = 0; i<correctAnswers.length; i++) {
    if (correctAnswers[i] == Answers[i]) { //if they're equal, push the value into the final array and remove the first value from the toChange array
        finalArray.push(Answers[i]);
        toChange.shift();
    } else { // if not, break
        break;
    }
}

Fiddle