如何在两个2d数组中找到匹配的列/行元素JavaScript的

时间:2015-06-03 15:00:02

标签: javascript arrays

我想在两个2d数组之间找到匹配的列元素

意味着我只想在那些给定数组中找到匹配的字符串值 我的数组是:

//chars : "stack"
var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];

// chars: "exchange"
var x = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3]];

这里是角色" a"在列中匹配,想要将其索引/值存储在变量

帮助,我怎样才能在JavaScript(不是jQuery)中

3 个答案:

答案 0 :(得分:1)

通过天真的暴力循环,您应该能够找到两个块之间的匹配,如下所示:

var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];
var y = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3]];


function intersection(ax,bx){
    var matches = [];
    ax.forEach(function (a,i){
        bx.forEach(function (b,j){
            if (a[0]===b[0]){ // NOTE: make sure you use STRICT EQUAL
                matches.push([a[0],[i,j],[a[1],b[1]]]);
            }
        });
    });
}

调用intersection(x,y)时,它应该为您提供一个如下所示的交集数组:

[['a',[2,4],[3,2]]]

第二个元素是匹配元素的索引[2,4] 其中第3个元素是值[3,2]

如果找到多个匹配项,您将获得以下所有匹配项:

[['a',[2,4],[3,2]], [['b',[3,5],[3,2]]]] // Just example

答案 1 :(得分:0)

试试这个

function getIndices(a, b) {
  function toObject(columns) {
    var o = {};
    columns.forEach(function(column, i) {
      var indices = o[column[0]] || [];
      indices.push(i);
      o[column[0]] = indices;
    });
    return o;
  }
  var oa = toObject(a),
      ob = toObject(b),
      result = [];
  Object.keys(oa).forEach(function(key) {
    if(ob[key]) result.push([key, oa[key], ob[key]]);
  });
  return result;
}

console.log(getIndices([["a", 1], ["b", 2], ["a", 5], ["c", 8]], [["c", 1], ["a", 2], ["d", 7], ["d", 9]]));

答案 2 :(得分:0)

//chars : "stack"
var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];

(function(){
// chars: "exchange"
var x = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3], ["a",7]];

  var result = {};
  for(var i = 0; i < x.length; ++i){
    var x_key = x[i][0];
    for(var j = 0; j < window.x.length; ++j){
      if (x_key == window.x[j][0]){
        
        result[x_key] = result[x_key] || [];
        result[x_key].push({index: i, value: x[i][1]});
      }
    }
  }
  
  alert(JSON.stringify(result))
})();;