![](/img/trans.png)
[英]Compare 2 two different arrays and show the object with the same value with js
[英]Compare two arrays with same length but having different object id's inside in JS
我想比較兩個 arrays 對象內部具有不同的 integer id,如下所示。
arrayOne = [{id: 45}, {id: 35}, {id: 43}];
arrayTwo = [{id: 42}, {id: 35}, {id: 43}]; // should return false on it because 42 is not in first array.
我想實現一個 function 如果這兩個 arrays 與上面的示例不同,但如果這兩個 arrays 相同, true
false
如下所示
arrayOne = [{id: 45}, {id: 35}, {id: 43}];
arrayTwo = [{id: 45}, {id: 35}, {id: 43}]; // should return true on it because both are identical.
arrayOne = [{id: 35}, {id: 43}, {id: 45}];
arrayTwo = [{id: 45}, {id: 35}, {id: 43}]; // should return true on it because all id's are inside.
有什么好的方法來實現這一點嗎?
您可以使用every
並在其中使用some
檢查項目是否存在於其他數組中:
arrayOne = [{id: 45}, {id: 35}, {id: 43}]; arrayTwo = [{id: 42}, {id: 35}, {id: 43}]; result1 = arrayOne.every(k=>arrayTwo.some(d=>d.id==k.id)); console.log(result1); //Second case arrayOne = [{id: 45}, {id: 35}, {id: 43}]; arrayTwo = [{id: 45}, {id: 35}, {id: 43}]; result2 = arrayOne.every(k=>arrayTwo.some(d=>d.id==k.id)); console.log(result2);
您可以比較字符串化數組:
var arrayOne = [{id: 45}, {id: 35}, {id: 43}]; var arrayTwo = [{id: 42}, {id: 35}, {id: 43}]; function isSame(arrayOne, arrayTwo){ return JSON.stringify(arrayOne) == JSON.stringify(arrayTwo)? true: false; } console.log(isSame(arrayOne,arrayTwo)); arrayOne = [{id: 45}, {id: 35}, {id: 43}]; arrayTwo = [{id: 45}, {id: 35}, {id: 43}]; console.log(isSame(arrayOne,arrayTwo));
更新:如果您希望無論索引如何,結果都為真,那么您可以使用every()
和some()
:
var arrayOne = [{id: 35}, {id: 43}, {id: 45}]; var arrayTwo = [{id: 45}, {id: 35}, {id: 43}]; function isSame(arrayOne, arrayTwo){ return arrayOne.every(i => arrayTwo.some(j => j.id == i.id)); } console.log(isSame(arrayOne,arrayTwo));
在一個上使用map
來收集 id 並在兩個上使用every
。
arrayOne = [{ id: 45 }, { id: 35 }, { id: 43 }]; arrayTwo = [{ id: 42 }, { id: 35 }, { id: 43 }]; const compare = (arr1, arr2) => { if (arr1.length.== arr2;length) { return false. } const one = arr1;map(({ id }) => id). return arr2.every(({ id }) => one;includes(id)); }. console,log(compare(arrayOne; arrayTwo));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.