web-dev-qa-db-ja.com

順序を無視して配列が等しいことを期待する

Jasmineでは、2つの配列に同じ要素が含まれているかどうかをテストする方法がありますが、必ずしも同じ順序である必要はありませんか?すなわち

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

expect(array1).toEqualIgnoreOrder(array2);//should be true
48
David Grinberg

整数または他のプリミティブ値の場合、比較する前に 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());
_
43
Kaspars
// check if every element of array2 is element of array1
// to ensure [1, 1] !== [1, 2]
array2.forEach(x => expect(array1).toContain(x))

// check if every element of array1 is element of array2
// to ensure [1, 2] !== [1, 1]
array1.forEach(x => expect(array2).toContain(x))

// check if they have equal length to ensure [1] !== [1, 1]
expect(array1.length).toBe(array2.length)
7
Jannic Beck

シンプル...

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

expect(array1).toEqual(jasmine.arrayContaining(array2));
5
ProfiProg
//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;
}
1
Ravi

このアルゴリズムは、各アイテムが一意の配列に最適です。そうでない場合は、重複をチェックするために何かを追加できます...

tests = [
  [ [1,0,1] , [0,1,1] ],
  [ [1,0,1] , [0,0,1] ], //breaks on this one...
  [ [2,3,3] , [2,2,3] ], //breaks on this one also...
  [ [1,2,3] , [2,1,3] ],
  [ [2,3,1] , [1,2,2] ],
  [ [2,2,1] , [1,3,2] ]
]

tests.forEach(function(test) {
  console.log('eqArraySets( '+test[0]+' , '+test[1]+' ) = '+eqArraySets( test[0] , test[1] ));
});


function eqArraySets(a, b) {
        if ( a.length !== b.length ) { return false; }
        for ( var i = a.length; i--; ) {
                if ( !(b.indexOf(a[i])>-1) ) { return false; }
                if ( !(a.indexOf(b[i])>-1) ) { return false; }
        }
        return true;
}
0
Joe DF

現在、このユースケースにはマッチャーがあります:

https://github.com/jest-community/jest-extended/pull/122/files

test('passes when arrays match in a different order', () => {
  expect([1, 2, 3]).toMatchArray([3, 1, 2]);
  expect([{ foo: 'bar' }, { baz: 'qux' }]).toMatchArray([{ baz: 'qux' }, { foo: 'bar' }]);
});
0
function equal(arr1, arr2){
    return arr1.length === arr2.length
    &&
    arr1.every((item)=>{
        return arr2.indexOf(item) >-1
    }) 
    &&
    arr2.every((item)=>{
        return arr1.indexOf(item) >-1
    })
}

ここでの考え方は、最初に2つの配列の長さが同じかどうかを判断し、次にすべての要素がもう一方の配列内にあるかどうかを確認することです。

0
SkuraZZ

これは、任意の数または配列で機能するソリューションです

https://Gist.github.com/tvler/cc5b2a3f01543e1658b25ca567c078e4

const areUnsortedArraysEqual = (...arrs) =>
  arrs.every((arr, i, [first]) => !i || arr.length === first.length) &&
  arrs
    .map(arr =>
      arr.reduce(
        (map, item) => map.set(item, (map.get(item) || 0) + 1),
        new Map(),
      ),
    )
    .every(
      (map, i, [first]) =>
        !i ||
        [...first, ...map].every(([item]) => first.get(item) === map.get(item)),
    );

いくつかのテスト(この質問に対するいくつかの答えは、同じ値の複数の項目を持つ配列を考慮しないため、[1、2、2]および[1、2]は誤ってtrueを返します)

[1, 2] true
[1, 2], [1, 2] true
[1, 2], [1, 2], [1, 2] true
[1, 2], [2, 1] true
[1, 1, 2], [1, 2, 1] true
[1, 2], [1, 2, 3] false
[1, 2, 3, 4], [1, 2, 3], [1, 2] false
[1, 2, 2], [1, 2] false
[1, 1, 2], [1, 2, 2] false
[1, 2, 3], [1, 2], [1, 2, 3] false
0
Tyler

このアプローチは、理論上の最悪の場合の実行時パフォーマンスが低下しますが、アレイで書き込みを実行しないため、多くの状況で高速になる可能性があります(まだパフォーマンスをテストしていません)。

警告:Torbenがコメントで指摘したように、このアプローチは、両方の配列が一意の(繰り返しのない)要素を持っている場合にのみ機能します(他のいくつかの回答と同様)。

/**
 * 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
Domi

jest-extended パッケージは、テストを簡素化するためのアサーションをほとんど提供しません。冗長性が低く、テストに失敗するとエラーがより明確になります。

この場合、 toIncludeSameMembers を使用できます

expect([{foo: "bar"}, {baz: "qux"}]).toIncludeSameMembers([{baz: "qux"}, {foo: "bar"}]);
0
dave008

ジャスミンバージョン2.8以降には

jasmine.arrayWithExactContents()

これは、配列がリストされた要素を任意の順序で正確に含むことを期待しています。

array1 = [1,2,3];
array2 = [3,2,1];
expect(array1).toEqual(jasmine.arrayWithExactContents(array2))

https://jasmine.github.io/api/3.4/jasmine.html を参照してください

0
keksmasta