在数组中的数组中查找交集元素

时间:2018-01-25 05:25:00

标签: javascript arrays

我需要构造一个函数交集,它比较输入数组并返回一个新数组,其中包含在所有输入中找到的元素。     如果在每个数组中数字只重复一次,则以下解决方案有效,否则会中断。另外,我不知道如何简化并且不使用凌乱的for循环:

function intersection(arrayOfArrays) {
  let joinedArray = [];
  let reducedArray = [];
  for (let iOuter in arrayOfArrays) {
    for (let iInner in arrayOfArrays[iOuter]) {
      joinedArray.push(arrayOfArrays[iOuter][iInner]);
    }
    return joinedArray;
  }


  for (let i in joinedArray.sort()) {
    if (joinedArray[i] === joinedArray[ i - (arrayOfArrays.length - 1)]) {
      reducedArray.push(joinedArray[i]);
    }
  }
  return reducedArray;
}

4 个答案:

答案 0 :(得分:0)

试试这个: -

var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
}
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
 }

答案 1 :(得分:0)

希望这段代码很有用

var a = [2, 3, 9];
var b = [2, 8, 9, 4, 1];
var c = [3, 4, 5, 1, 2, 1, 9];
var d = [1, 2]

function intersect() {
  // create an empty array to store any input array,All the comparasion
  // will be done against this one
  var initialArray = [];
  // Convert all the arguments object to array
  // there can be n number of supplied input array
  // sorting the array by it's length. the shortest array 
  //will have at least all the elements
  var x = Array.prototype.slice.call(arguments).sort(function(a, b) {
    return a.length - b.length
  });
  initialArray = x[0];
  // loop over remaining array
  for (var i = 1; i < x.length; i++) {
    var tempArray = x[i];
    // now check if every element of the initial array is present
    // in rest of the arrays
    initialArray.forEach(function(item, index) {
      // if there is some element which is present in intial arrat but not in current array
      // remove that eleemnt.
      //because intersection requires element to present in all arrays
      if (x[i].indexOf(item) === -1) {
        initialArray.splice(index, 1)
      }

    })

  }
  return initialArray;
}

console.log(intersect(a, b, c, d))

答案 2 :(得分:0)

有一种很好的方法可以使用reduce与数组数组相交,然后filter使其余值保持唯一。

function intersection(arrayOfArrays) {
    return arrayOfArrays
        .reduce((acc,array,index) => { // Intersect arrays
            if (index === 0)
                return array;
            return array.filter((value) => acc.includes(value));
        }, [])
        .filter((value, index, self) => self.indexOf(value) === index) // Make values unique
    ;
}

答案 3 :(得分:0)

您可以迭代每个数组并计算对象中出现数字的频率,其中键是数组中的数字,其属性是数组中出现的数组。使用生成的对象找出每个数字的最低频率,并检查其值是否大于零,并将该数字添加到结果中。

function intersection(arrayOfArrays) {
  const frequency = arrayOfArrays.reduce((r, a, i) => {
    a.forEach(v => {
      if(!(v in r))
        r[v] = Array.from({length:arrayOfArrays.length}).fill(0);
      r[v][i] = r[v][i] + 1;
    });
    return r;
  }, {});
  
  return Object.keys(frequency).reduce((r,k) => {
    const minCount = Math.min(...frequency[k]);
    if(minCount) {
      r = r.concat(Array.from({length: minCount}).fill(+k));
    }
    return r;
    }, []);
}
console.log(intersection([[2,3, 45, 45, 5],[4,5,45, 45, 45, 6,7], [3, 7, 5,45, 45, 45, 45,7]]))