![](/img/trans.png)
[英]How to find out if there are unequal items by comparing the items of two arrays in JavaScript?
[英]Comparing two arrays and getting out missing/wrong items
我對 Js 數組沒什么問題。 我有兩個數組 - 一個始終正確(使用正確的數據創建),一個基本上來自獲取。 我正在嘗試比較這兩個數組,我能夠得到它們匹配的項目,但不能得到不匹配的項目:
var results = [];
var controlArray = ['T', 'M', 'P', 'N']
var fetchArray = ['T', 'M', 'PP', 'N ']
for (var i = 0; i < controlArray.length; i++) {
for (var j = 0; j < fetchArray.length; j++) {
if (controlArray[i] === fetchArray[j]) {
results.push(fetchArray[i]);
}
}
}
輸出應該是這樣的:
results = ['PP', 'N '];
或者:
results = ['P', 'N'];
所以它會指出問題出在哪里。 這兩個都可以工作。
這給了我匹配的部分。 我試圖只放 !== 但在這種情況下,它會多次拋出基本上所有的東西,我看不出為什么它不應該這樣工作的邏輯。 留白也很重要。
有什么想法可以輕松地從這些數組中獲取不匹配的值?
您應該循環遍歷數組並使用包含進行過濾。 例如:
const results = fetchArray.filter(el => !controlArray.includes(el));
// results: ['PP', 'N ']
希望能幫助到你..
它確實返回的原因是您將一個數組的元素與另一個數組的所有其他元素進行了比較。
var results = [];
var controlArray = ['T', 'M', 'P', 'N']
var fetchArray = ['T', 'M', 'PP', 'N ']
for (var i = 0; i < controlArray.length; i++) {
for (var j = 0; j < fetchArray.length; j++) {
if (controlArray[i] === fetchArray[j]) {
results.push(fetchArray[i]);
}
}
}
而不是這個,您應該只使用一個索引來比較兩個數組。
var results = []; var controlArray = ['T', 'M', 'P', 'N'] var fetchArray = ['T', 'M', 'PP', 'N '] for (var i = 0; i < controlArray.length; i++) { if (controlArray[i] !== fetchArray[i]) { results.push(fetchArray[i]); } } console.log(results)
來自 fetchArray 但不在 controlArray 中的項目
fetchArray.forEach(function(it){
controlArray.indexOf(it)==-1&&results.push(it)
})// results: ['PP', 'N ']
來自 controlArray 但不在 fetchArray 中的項目
controlArray.forEach(function(it){
fetchArray.indexOf(it)==-1&&results.push(it)
})// results: ['P', 'N']
const controlArray = ['T', 'M', 'P', 'N']; const fetchArray = ['T', 'M', 'PP', 'N ']; const match = fetchArray.filter(value => !!controlArray.find(controlValue => value === controlValue)) const noMatch = fetchArray.filter(value => !controlArray.find(controlValue => value === controlValue)); console.log({ match, noMatch })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.