如何使用javascript匹配两个数组的字符串值

时间:2015-03-18 17:30:27

标签: javascript arrays

我有两个数组

var arr1 = ['wq','qw','qq'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];

我所做的就是将arr1值与arr2匹配。如果数组包含相同的值,我将值推送到newArr

var newArr = [];
for (var i=0;i<arr1.length;i++) {
    newArr[i] = [];
}

for (var i=0;i<arr2.length;i++) {
    for (var j=0;j<arr1.length;j++) {
        if (arr2[i].indexOf(arr1[j]) != -1)
            newArr[j].push(arr2[i]);
    }
}
console.log(newArr[1]); //newArr[0] = ['wq','wq','wq'];//In second output array newArr[1] = ['qw','qw','qw','qw'];

有没有简单的方法可以在不使用两个for循环的情况下解决这个问题。更好,我需要一个javascript的解决方案

3 个答案:

答案 0 :(得分:1)

也许使用indexOf()

var count = 0;
for (var i = 0; i < arr1.length; i++) {
    if (arr2.indexOf(arr1[i]) != -1) {
        count++;
        // if you just need a value to be present in both arrays to add it
        // to the new array, then you can do it here
        // arr1[i] will be in both arrays if you enter this if clause
    }
}

if (count == arr1.length) {
    // all array 1 values are present in array 2
} else {
    // some or all values of array 1 are not present in array 2
}

答案 1 :(得分:1)

你自己的方式并非完全错误,你只需要检查元素是否是数组的索引而不是数组中的元素。

var arr1 = ['wq','qw','qq'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];
var newArr = [];

for (var i in arr1) {
    newArr[i] = [];
}

for (var i in arr2) {
    var j = arr1.indexOf(arr2[i]);
    if (j != -1) {
        newArr[j].push(arr2[i]);
    }
}

这样你就删除了嵌套的for循环,它仍然可以提供你要求的结果。

答案 2 :(得分:0)

var arr1 = ['wq','qw','qq','pppp']; 
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];

function intersect(a, b) {
var d = {};
var results = [];
for (var i = 0; i d[b[i]] = true;
}
for (var j = 0; j if (d[a[j]])
results.push(a[j]);
}
return results;
}

var result_array = intersect(arr1,arr2);

// result_array will be like you want ['wq','wq','wq'];