0

I want to check if below two arrays are same or not in typescript. if condition is failing as per below code. Please let me know how to resolve this:

let props:(string|boolean)[]=['abc','def',true,false,'xyz']
let propsCopied:(string|boolean)[]=['abc','def',true,false,'xyz']
let allPropsCopied:boolean;

if(props===propsCopied){
allPropsCopied=true;
}
Rahul
  • 759
  • 3
  • 21
  • 43
  • `===` operator checks for object identity, not object equality. It checks if the two variables refer to the same object in memory. Please take a look at similar question https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript – Invulner Mar 06 '23 at 10:38

3 Answers3

1

You can use this short way:

JSON.stringify(props)===JSON.stringify(propsCopied)

or use complete and better way:

function isArrayEqual(a:(string|boolean)[], b:(string|boolean)[]) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;

  // If you don't care about the order of the elements inside
  // the array, you should sort both arrays here.
  // Please note that calling sort on an array will modify that array.
  // you might want to clone your array first.

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}
Sektowr
  • 356
  • 1
  • 8
  • Why are you checking for null/undefined when arrays (even if empty) are never nullable? That would only be necessary if the type was `(string|boolean)[] | undefined` – Asplund Mar 06 '23 at 10:50
  • You're right . i copied this code from a js code . I forgot this is type script :) – Sektowr Mar 06 '23 at 10:53
1

The typescript version of the answer in linked question:

function arraysEqual<T>(a: T[] | null, b: T[] | null): bool {
  if (a === b) {
    return true;
  }
  if (a == null || b == null || a.length !== b.length) {
    return false;
  }

  // If you don't care about the order of the elements inside
  // This is not strict. Need to count the number of every elements if need strict.
  // return a.every(i => b.some(i)) && b.every(i => a.some(i));
 

  for (let i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) {
      return false;
    };
  }
  return true;
}

For you code:

let props:(string|boolean)[]=['abc','def',true,false,'xyz']
let propsCopied:(string|boolean)[]=['abc','def',true,false,'xyz']
let allPropsCopied:boolean = arraysEqual(props, propsCopied);
LiHS
  • 134
  • 6
0

This worked for me 'JSON.stringify(props)===JSON.stringify(propsCopied)'

Rahul
  • 759
  • 3
  • 21
  • 43