Javascript:在多个数组

时间:2015-12-28 16:24:58

标签: javascript arrays compare

这应该做的是接收一个填充了一个字母值的二维数组,并返回所有共享值的数组。这就是我到目前为止所做的:

var res = array[0].filter(function(x){
        return array.every(function(y){
             return y.indexOf(x) >= 0
        })
    });
return res;  

这是某种形式的工作状态,但只有在某种条件下才能使其受到重创。 按预期工作:

var array = [["x","x"],
             ["x","x","x"]];

这将返回预期的[“x”,“x”]数组,但是这样的话:

var array = [["x","x","x"],
             ["x","x"]];

返回[“x”,“x”,“x”]

正如您所看到的,这两个数组只共享2个常见的x,但代码在不同情况下并未反映出来。它也应该能够像其他字母一样处理数组:

var array = [["x","x","z","y","y"],
             ["x,"x","x","y"],
             ["x","x","z","y"]];

有这样的东西它应该返回[“x”,“x”,“y”],因为所有数组共享2个常见的x和1个共同的y

3 个答案:

答案 0 :(得分:2)

使用.every.filter的组合,使用.indexOf检查数组中是否存在元素。

var array = [
  ["x", "x", "z", "y", "y"],
  ["x", "x", "x", "y"],
  ["x", "x", "z", "y"]
];

var res = array[0].filter(function(x) {
  return array.every(function(y) {
    if (y.indexOf(x) != -1) {
      y[y.indexOf(x)] = Infinity;
      return true;
    }
    return false;
  })
})

alert(res)

答案 1 :(得分:0)

这是另一种方法,使用只能从IE9等获得的Array方法。

function compareValues() {
    var arrs = [].slice.call(arguments).sort(function(a,b) {
    	return a.length > b.length; // always iterate shortest array
    });
    
    return arrs.shift().filter(function(x, i) { // filter the first array
    	return arrs.every(function(arr) {       // if all other arrays
       	    return arr[i] === x;                // have the same value at the same index
        })
    });
}

var result = compareValues(["x","x","x","y"], 
                           ["x","x","z","y"], 
                           ["x","x","z","y","y"]);

alert(result);

答案 2 :(得分:0)

这是一项针对非破坏性搜索的Array.prototype.reduce()Array.prototype.filter()Array.prototype.indexOf()提案。



var array = [
        ["x", "x", "z", "y", "y"],
        ["x", "x", "x", "y"],
        ["x", "x", "z", "y"]
    ],
    result = array.reduce(function (r, a) {
        var last = {};
        return r.filter(function (b) {
            var p = a.indexOf(b, last[b] || 0);
            if (~p) {
                last[b] = p + 1;
                return true;
            }
        });
    });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;