比较两个数组中的元素

时间:2016-05-15 07:22:55

标签: javascript arrays

我想将数组real的每个元素与数组编号的每个元素进行比较。如果有任何匹配,请将它们添加到数组中,以便我可以看到它们。在这种情况下,如果代码良好,则add必须为2,3,6,10,14。

    <!DOCTYPE html>
    <html>
    <head>
    </head>
        <body>
        <script>
        var real=[1,2,3,4,5,6,7,8,10,14,16,233,235,245,2,5,7,236,237];
        var number=[2,3,6,10,12,13,14,172,122,234];
        var add=[];
        for (k=0; k<number.length; k++)
                { 
                    for (w=0; w<real.length; w++)
                        { 
                            if (number[k]==real[w]); 
                                {
                                    add.push(number[k],real[w]);
                                }
                        };

                };
        document.write(add+"<br>");
        </script>

4 个答案:

答案 0 :(得分:2)

以下是使用Array.forEachArray.indexOf函数的简短解决方案:

var real = [1,2,3,4,5,6,7,8,10,14,16,233,235,245,2,5,7,236,237],
    number = [2,3,6,10,12,13,14,172,122,234],
    add = [];

real.forEach(function(v) {
    if (number.indexOf(v) !== -1 && this.indexOf(v) === -1) this.push(v);
}, add);

console.log(add);   // [2, 3, 6, 10, 14]

答案 1 :(得分:0)

更优雅,更易读的解决方案:

var matched = [];
real.forEach(function(realNum) {
    number.forEach(function(numberNum) {
        if(realNum == numberNum && matched.indexOf(realNum) === -1) {
            matched.push(realNum);   
        }                     
    });
});

答案 2 :(得分:0)

以下是使用ES6进行此操作的一种方法:

var real = [1, 2, 3, 4, 5, 6, 7, 8, 10, 14, 16, 233, 235, 245, 2, 5, 7, 236, 237];
var number = [2, 3, 6, 10, 12, 13, 14, 172, 122, 234];

var filtered = real.filter(x => number.indexOf(x) > -1);
var unique = new Set(filtered);

document.body.innerHTML = [...unique];

答案 3 :(得分:0)

尝试这种方式...... 对主Array进行排序,删除重复项并从两个数组中查找公共元素。

var main = [1,2,3,4,5,6,7,8,10,14,16,233,235,245,2,5,7,236,237];
var compare = [2,3,6,10,12,13,14,172,122,234];

function compareNumbers(a, b) {
  return a - b;
}
console.log('Sorted Array :', main.sort(compareNumbers) );
// Sorted Array : [1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 10, 14, 16, 233, 235, 236, 237, 245]

Array.prototype.unique = function() {
    var unique = [];
    for (var i = 0; i < this.length; i++) {
        var current = this[i];
        if (unique.indexOf(current) < 0) unique.push(current);
    }
    return unique;
}    
console.log('Unique Array Elements:', main.unique() );
// Unique Array Elements: [1, 2, 3, 4, 5, 6, 7, 8, 10, 14, 16, 233, 235, 236, 237, 245]

function commonElements(arr1, arr2) {
    var common = [];
    for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
            if (arr1[i] == arr2[j] ) {
                common.push( arr1[i] );
                j == arr2.length; // To break the loop;
            }
        }
    }
    return common;
}

console.log('Common Elements from Both Arrays : ', commonElements(main.unique(), compare.unique()) );
//Common Elements from Both Arrays :  [2, 3, 6, 10, 14]