2015-08-19 67 views
17

用Jasmine有沒有辦法測試2個數組是否包含相同的元素,但不一定是相同的順序?即期望數組相等忽略次序

array1 = [1,2,3]; 
array2 = [3,2,1]; 

expect(array1).toEqualIgnoreOrder(array2);//should be true 
+11

'expect(array1.sort())。toEqual(array2.sort());'? – raina77ow

+0

@ raina77ow我想這也可以。 –

+1

我應該做出這個答案嗎? – raina77ow

回答

1
//Compare arrays without order 
//Example 
//a1 = [1, 2, 3, 4, 5] 
//a2 = [3, 2, 1, 5, 4] 
//isEqual(a1, a2) -> true 
//a1 = [1, 2, 3, 4, 5]; 
//a2 = [3, 2, 1, 5, 4, 6]; 
//isEqual(a1, a2) -> false 


function isInArray(a, e) { 
    for (var i = a.length; i--;) { 
    if (a[i] === e) return true; 
    } 
    return false; 
} 

function isEqArrays(a1, a2) { 
    if (a1.length !== a2.length) { 
    return false; 
    } 
    for (var i = a1.length; i--;) { 
    if (!isInArray(a2, a1[i])) { 
     return false; 
    } 
    } 
    return true; 
} 
16

如果它只是整數或其他原始值,可以在比較之前sort()他們。

expect(array1.sort()).toEqual(array2.sort()); 

如果它的對象,與map()功能結合起來,以提取進行比較

array1 = [{id:1}, {id:2}, {id:3}]; 
array2 = [{id:3}, {id:2}, {id:1}]; 

expect(array1.map(a => a.id).sort()).toEqual(array2.map(a => a.id).sort()); 
0

排序兩個數組首先是做這件事的一種方式的標識,但它創造了很多份,因此對性能不利。

這有惡化的最壞情況運行時的性能,但很可能會在大多數情況下更快,當數組不是非常大,沒有太多的不同依次爲:

/** 
 
* Determine whether two arrays contain exactly the same elements, independent of order. 
 
* @see https://stackoverflow.com/questions/32103252/expect-arrays-to-be-equal-ignoring-order/48973444#48973444 
 
*/ 
 
function cmpIgnoreOrder(a, b) { 
 
    const { every, includes } = _; 
 
    return a.length === b.length && every(a, v => includes(b, v)); 
 
} 
 

 
// the following should be all true! 
 
const results = [ 
 
    !!cmpIgnoreOrder([1,2,3], [3,1,2]), 
 
    !!cmpIgnoreOrder([4,1,2,3], [3,4,1,2]), 
 
    !!cmpIgnoreOrder([], []), 
 
    !cmpIgnoreOrder([1,2,3], [3,4,1,2]), 
 
    !cmpIgnoreOrder([1], []), 
 
    !cmpIgnoreOrder([1, 3, 4], [3,4,5]) 
 
]; 
 

 
console.log('Results: ', results) 
 
console.assert(_.reduce(results, (a, b) => a && b, true), 'Test did not pass!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

0
// check if every element of array to is element of array1 
array2.map(x => expect(array1).toContain(x)) 

// check if they have equal length since array1 could be a superset of array2 
expect(array1.length).toBe(array2.length) 
0

對於它的價值,是開玩笑,你可以這樣做:

expect(new Set([1,2,3])).toEqual(new Set([[3,2,1]))