检查一个数组中的值在另一个数组中出现了多少次

Check how many times a value in an array appears in another array

我想看看一个数组中的值在另一个数组中出现了多少次。这是我的一件事,但没有用。

arr1 = [1, 2, 3, 4, 5];

arr2 = [1, 7, 8, 9, 10];


count = 0;

for (x in arr2){
        for (y in arr1){
                if (x == y){
                        count +=1;
                }
        }
}

console.log(count);

我试过的另一件事是这个。

(arr1.some((val)=>{return arr2.includes(val);} ))

它检查是否至少有一个值匹配,但我不确定如何为它实现计数。

我的目标是查看 arr2 中的值在 arr1 中出现了多少次。在这种情况下应该 return 1

您可以使用 Array.prototype.reduce in combination with Array.prototype.filter 来获取重复值的对象

const arr1 = [1, 2, 3, 4, 5, 1, 1, 1, 9, 9]; // Repeated values
const arr2 = [1, 7, 8, 9, 10]; // Unique values

const appearances = (arrUnique, arrRepeated) => arrUnique.reduce((ob, valUnique) => {
  ob[valUnique] = arrRepeated.filter(v => valUnique === v).length;
  return ob;
}, {});

console.log(appearances(arr2, arr1));    // {value: counts, ...}
console.log(appearances(arr2, arr1)[1]); // 4

这将 return:

{
  "1": 4,   // repeats 4 times
  "7": 0,
  "8": 0,
  "9": 2,   // repeats 2 times
  "10": 0
}

x 和 y 将是使用此语法时循环的索引。 所以,在你能做到这一点之后,得到你现在的样子。

    const arr1 = [1, 2, 3, 4, 5];

const arr2 = [1, 7, 8, 9, 10];


count = 0;

for (x in arr2){
        for (y in arr1){
                if (arr2[x] === arr1[y]){
                        count +=1;
                }
        }
}

console.log(count);

 

您可以从计数值中取出一个对象,然后迭代第二个数组并只计算想要的值。

const
    array1 = [1, 2, 3, 4, 5],
    array2 = [1, 7, 8, 9, 10],
    result = array1.reduce(
        (r, v) => (v in r && r[v]++, r),
        Object.fromEntries(array2.map(v => [v, 0]))
    );

console.log(result);

详细信息在示例中注释并打印在控制台上。使用 reduce()Map() 概念来自 here.

// Utility function
const log = data => console.log(JSON.stringify(data));

log(`const arr1 = [1, 2, 3, 4, 5];`);
log(`const arr2 = [1, 7, 8, 9, 10];`);
log(`const arr3 = [1, 2, 3, 4, 5, 6, 7];`)
log(`const arr4 = [1, 7, 8, 9, 10];`);

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 7, 8, 9, 10];
const arr3 = [1, 2, 3, 4, 5, 6, 7];
const arr4 = [1, 7, 8, 9, 10];

const times = (arrA, arrB) => 
  // Returns n if...  
  arrB.filter(n => 
    // ...n exists in arrA
    arrA.includes(n))
    // Return how many matches
    .length;
    
log(`@param: arr1, arr2`)
log(times(arr1, arr2));
log(`@param: arr3, arr4`)
log(times(arr3, arr4));

// ...Rest operator will accept an unlimited amount
const frequency = (...arrays) => {
  // Combine params into one array
  let array = [...arrays.flat()],
  min;
  // If the first param is a string...
  if (''+array[0] === array[0]) {
    /*
    ...remove it from the array and convert it into a number.
    Otherwise it's 1
    */
    min = +array.shift();
  } else min = 1;
  
  // 4. Convert Map into an array of [key, value] pairs
  return  [...array
    .reduce((grp, val) => 
      /*
      3. Set [value] on Map to the it's current value +1
      */
      grp.set(val, 
        /*
        2. Get [value] from Map, but if it doesn't exist yet then it's a 
           zero.
        */
        (grp.get(val) || 0) + 1)
        // 1. Create Map object
        , new Map()
    )]
    // 5. Return each pair that meets or exceeds min
    .filter(([key, val]) => val >= min);
}

log(`@param: arr1, arr2`);
log(frequency(arr1, arr2));

log(`@param: arr3, arr4`);
log(frequency(arr3, arr4));

log(`frequency() will accept anything in unlimited amounts`);
log(`@param: arr1, arr2, arr3, arr4, 10, 8`);
log(frequency(arr1, arr2, arr3, arr4, 10, 8));

log(`Pass first parameter as a string of a number if you want a minimum count returned`);
log(`@param: '2', arr3, arr4`);
log(frequency('2', arr3, arr4));

log(`If you want use an object instead an array pairs, use Object.fromEntries(frequency(arr1, arr2))`);
log(Object.fromEntries(frequency(arr1, arr2)));
.as-console-row::after { width: 0; font-size: 0; }
.as-console-row-code { width: 100%; word-break: break-word; }
.as-console-wrapper { min-height: 100% !important; min-width: 100%; }