2

i have two arrays and want to check if all IDs is the same or not

let a = [
          {id:0, name:"test0"},
          {id:1, name:"test1"}
         ];

let b = [
          {id:0, name:"test0"},
          {id:1, name:"test1"}
         ];

the above arrays we see it's equal

and the way I tired like this

JSON.stringify(a) === JSON.stringify(b) => True

I read the JSON.stringify it's affected the Performance if we have big arrays

so is there another way to get the same result?

Oliver D
  • 2,579
  • 6
  • 37
  • 80

1 Answers1

2

const areEqual = (a = [], b = []) => {
  // compare length of arrays
  if(a.length !== b.length) {
    return false;
  }
  // get sorted lists of ids
  const arr1 = a.map(({id}) => id).sort(), arr2 = b.map(({id}) => id).sort();
  // iterate over the arrays and compare, if at an index, items mismatch, return false
  for(let i = 0; i < arr1.length; i++) {
    if(arr1[i] !== arr2[i]) {
      return false;
    }
  }
  // if it passes all the items, return true
  return true;
}

console.log( 
  areEqual(
    [{id:0, name:"test0"}, {id:1, name:"test1"}], 
    [{id:0, name:"test0"}, {id:1, name:"test1"}]
  )
);

Another solution using Set:

const areEqual = (a = [], b = []) => {
  // compare length of arrays
  if(a.length !== b.length) {
    return false;
  }
  // get ids set in b
  const idsSetInB = new Set(b.map(({id}) => id));
  // iterate over a, and check if the id of an item is not in b
  for(let {id} of a) {
    if(!idsSetInB.has(id)) {
      return false;
    }
  }
  // if it passes all the items, return true
  return true;
}

console.log( 
  areEqual(
    [{id:0, name:"test0"}, {id:1, name:"test1"}], 
    [{id:1, name:"test1"}, {id:0, name:"test0"}]
  )
);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48