如果某些元素在另一个数组中,如何合并循环数组中的元素?

时间:2016-06-11 17:51:02

标签: javascript arrays

我有一个这样的数组:

var arr = [
        [11, 12, 13, 14], 
        [1, 2, 3, 4], 
        [3, 4, 5], 
        [5, 6, 7, 8],
        [6, 7, 8 , 9]
];

我想连接另一个数组中有值的数组并删除它的副本,所以在这种情况下它应该输出:

var arr = [
            [11, 12, 13, 14], 
            [1, 2, 3, 4, 5, 6, 7, 8, 9] 

    ];

任何帮助将不胜感激。谢谢!

4 个答案:

答案 0 :(得分:1)

你可以做这样的事情

var arr = [
  [11, 12, 13, 14],
  [1, 2, 3, 4],
  [3, 4, 5],
  [5, 6, 7, 8],
  [6, 7, 8, 9]
];

// iterate and generate the array
var res = arr.reduce(function(r, el) {
  var ind;
  // check any elemnt found in already pushed array elements
  if (r.some(function(v, i) {
    // cache the index if match found we need to use this for concatenating 
    ind = i;
    return v.some(function(v1) {
      return el.indexOf(v1) > -1;
    })
  })) {
    // if element found then concat and filter to avoid duplicates
    r[ind] = r[ind].concat(el).filter(function(v, i, arr1) {
      return arr1.indexOf(v) == i;
    })
  } else
  // otherwise filter and push the array
    r.push(el.filter(function(v, i, arr1) {
    return arr1.indexOf(v) == i;
  }))
  return r
}, []);

console.log(res);

答案 1 :(得分:0)

如果你这样使用,所有都会出现在一个没有重复值的数组中。它可能会帮助你

   <script>
    var arr = [
        [11, 12, 13, 14],
        [1, 2, 3, 4],
        [3, 4, 5],
        [5, 6, 7, 8],
        [6, 7, 8, 9]
    ];
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
        newArr = newArr.concat(arr[i]);
    }
    var tmp = [];
    for (var i = 0; i < newArr.length; i++) {
        if (tmp.indexOf(newArr[i]) == -1) {
            tmp.push(newArr[i]);
        }
    }
    alert(tmp);
    </script>

答案 2 :(得分:0)

没有indexOf的提案。

&#13;
&#13;
var arr = [[11, 12, 13, 14], [1, 2, 3, 4], [3, 4, 5], [5, 6, 7, 8], [6, 7, 8, 9]],
    temp = Object.create(null), i = 0, index;

while (i < arr.length) {
    if (arr[i].some(function (b) {
        if (b in temp) {
            index = temp[b];            
            return true;
        }
        temp[b] = i;
    })) {
        arr[i].forEach(function (b) {
            if (temp[b] !== index) {
                arr[index].push(b);
                temp[b] = index;
            }                    
        });
        arr.splice(i, 1);
        continue;
    }
    i++;
}
    
console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我想通过引入Array.prototype.intersect()方法来实现这一点。

&#13;
&#13;
Array.prototype.intersect = function(a) {
  return this.filter(e => a.includes(e));
};

var arr = [
        [11, 12, 13, 14], 
        [1, 2, 3, 4], 
        [3, 4, 5], 
        [5, 6, 7, 8],
        [6, 7, 8 , 9]
],
    res = [];

res.push(Array.from(new Set(arr.reduce((p,c) => p.intersect(c)[0] ? p.concat(c) : (res.push(Array.from(new Set(p))),c)))));
console.log(JSON.stringify(res));
&#13;
&#13;
&#13;

当然,正如您所猜测的那样,Array.from(new Set(p))会返回p数组中删除的数据。