JavaScript. How to Compare Input Arrays

我怕爱的太早我们不能终老 提交于 2019-12-01 07:34:09

问题


I'm stuck with this problem for 3 days now... Someone please help me.

Challenge 5
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

function intersection(arrayOfArrays) {

}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

// should log: [5, 15]

回答1:


You could reduce the array by filtering with just checking if the other array contains the value.

This works for arrays with unique values.

Array#reduce:

If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

The callback

a.filter(v => b.includes(v))

filters array a. If the array b includes the value of a, then this value v is included in the accumulator for the next iteration or as final result.

     accumulator            currentValue           new accumulator
          a                       b                    result
--------------------    --------------------    --------------------
[     5, 10, 15, 20]    [15, 88,  1,  5,  7]    [             5, 15]
[             5, 15]    [ 1, 10, 15,  5, 20]    [             5, 15]

function intersection(arrayOfArrays) {
    return arrayOfArrays.reduce((a, b) => a.filter(v => b.includes(v)));
}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));



回答2:


Reduce the arrays to a Map of counts, with the value as key. Spread the Map to entries. Use Array.filter() on the Map's entries to remove all entries, which value is not equal to the arrayOfArrays lenth. Extract the original number from the entries using Array.map():

function intersection(arrayOfArrays) {
  return [...arrayOfArrays.reduce((r, s) => {
    s.forEach((n) => r.set(n, (r.get(n) || 0) + 1));
    
    return r;
  }, new Map())]
  .filter(([k, v]) => v === arrayOfArrays.length)
  .map(([k]) => k);
}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));



回答3:


First try to find out the intersection of two arrays which is the base problem. Then try to build up for variable number of arrays passed as arguments for intersection. You can use reduce() for doing that.

function intersectionOfTwoArrays(arr1, arr2)
{
   return arr1.filter(x => arr2.some(y => y === x)); 
}


function intersection(...arrayOfArrays)
{
	return arrayOfArrays
	       .reduce((a, b) => intersectionOfTwoArrays(a, b));
}

intersection(
[5, 10, 15, 20], 
[15, 88, 1, 5, 7], 
[1, 10, 15, 5, 20]
);



回答4:


You can go through the first array in the array of arrays and check which of its value is present in all the other arrays.

Here is an example:

function intersection(input) {
    let firstArray = input[0];
    let restOfArrays = input.splice(1);
    return firstArray.filter(v => restOfArrays.every(arr => arr.includes(v)));    
}

const input = [[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]];
const result = intersection(input);

console.log(result);



回答5:


Works with even if there is duplicate in same array.. like in my example added 5 twice in arrayEle[1];

var arrayEle = [[5, 10, 15, 20], [15, 88, 1, 5, 5], [1, 10, 15, 5, 20]]
var startIndex = 1;
var newArray = [];
for (var x = 0; x < arrayEle[0].length; x++) {
  var temVal = 1;
  var value;
  for (var y = 1; y < arrayEle.length; y++) {
    for (var z = 0; z < arrayEle[y].length; z++) {
      if (arrayEle[y][z] == arrayEle[0][x]) {
        temVal++;
        value = arrayEle[y][z];
        break;
      }
    }
  }
  if (temVal == arrayEle.length) {
    newArray.push(value);
    console.log(value);
  }
}
console.log(newArray);


//log: [5, 15]



回答6:


I think you want the common elements. Let me show you how:

var Array1 = [5, 10, 15, 20]
var Array2 = [15, 88, 1, 5, 7]
var Array3 = [1, 10, 15, 5, 20]
var found = []
var Final = []
var c = 1;e = 1;
for (i = 1;i<=Array1.length;i++){
    for (k = 1;k<=Array2.length;i++){
        if (Array1[i] == Array2[k]){
            Found[c] = Array[i];
            c++;
        }
    }
}
for (n = 1;n <= Found.length ; n++){
    for (m = 1;m <= Array3.length ; n++){
        if (Found[n] == Array3[m]){
            Final[e] = Found[n]
            e++; 
        }
    }
}
//the Array Final Contains 5 , 15


来源:https://stackoverflow.com/questions/50298542/javascript-how-to-compare-input-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!