簡體   English   中英

檢查一個數組中的值在另一個數組中出現的次數

[英]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中的次數。 在這種情況下,它應該返回1

您可以將Array.prototype.reduceArray.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

這將返回:

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

您可以從計數值中獲取一個對象,然后迭代第二個數組並只計算想要的值。

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

使用此語法時,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);

 

詳細信息在示例中進行了注釋並打印在控制台上。 使用reduce()Map()的概念來自這里

 // 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%; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM