比较两个数组并仅显示匹配项Jquery

时间:2013-12-11 18:21:56

标签: javascript jquery arrays

var rundhalsArray = ["50237451_001", "50237451_100"];
var Array = ["50237451_001", "50237451_100", "50236765_001", "50236765_100"];

我有两个数组,并且只想在比较它们时显示匹配的项目,所以上面的结果将是:

var resultArray = ["50237451_001", "50237451_100"];

2 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/kL69J/

我就是这样做的:

var array1 = ["a", "b", "c", "d", "e", "f"];
var array2 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
var foo = [];

$.grep(array2, function(el) {

    if ($.inArray(el, array1) != -1) {
        foo.push(el);
    }

});


alert(" they have the same " + foo);

答案 1 :(得分:1)

<强> JSFIDDLE DEMO

var rundhalsArray = ["50237451_001", "50237451_100"];
var arr = ["50237451_001", "50237451_100", "50236765_001", "50236765_100"];

var result = [];
$.map(rundhalsArray, function (val, i) {
    if ($.inArray(val, arr) > -1) {
        result.push(val);
    }
});
console.log(result);