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



我有一个这样的数组:

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] 
    ];

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

你可以做这样的事情

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);

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

   <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>

没有indexOf的提案。

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);

我想

通过引入Array.prototype.intersect()方法来做到这一点。

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));

当然,正如您所猜测的那样,Array.from(new Set(p))会返回删除的p阵列重复。

最新更新