Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if Array are equal – Javascript

I have an array, and i need to check if Array[A] is same or not with Array[B]

Here’s my array in console:

Array A

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Array B

enter image description here

and when i console.log, i got
false

and here’s my code to check the array:

const [listA, setListA] = useState([
    { id: 1, color: "white" },
    { id: 2, color: "red" },
    { id: 3, color: "red" },
    { id: 4, color: "blue" },
    { id: 5, color: "red" },
    { id: 6, color: "red" },
    { id: 7, color: "red" },
    { id: 8, color: "blue" },
    { id: 9, color: "red" },
    { id: 10, color: "red" },
    { id: 11, color: "red" },
    { id: 12, color: "blue" },
    { id: 13, color: "red" },
    { id: 14, color: "red" },
    { id: 15, color: "red" },
    { id: 16, color: "red" },
  ]);

  const [listB, setListB] = useState([
    { id: 1, color: "white" },
    { id: 2, color: "red" },
    { id: 3, color: "red" },
    { id: 4, color: "blue" },
    { id: 5, color: "red" },
    { id: 6, color: "red" },
    { id: 7, color: "red" },
    { id: 8, color: "blue" },
    { id: 9, color: "red" },
    { id: 10, color: "red" },
    { id: 11, color: "red" },
    { id: 12, color: "blue" },
    { id: 13, color: "red" },
    { id: 14, color: "red" },
    { id: 15, color: "red" },
    { id: 16, color: "red" },
  ]);

const checkArray = async (newArr) => {
    console.log(listA === listB);
    // i got false

    // another attempt:
     const is_same =
      listA.length == listB &&
      listA.every(function (element, index) {
        return element === listB[index];
      });
     console.log(is_same)
    // i got false
  };

to be honest, i still didn’t know what is wrong,

but when i do check listA === listA, the console said true

>Solution :

You need to change it to

 const is_same =
      listA.length == listB.length &&
      listA.every(function (element, index) {
        return element.color === listB[index].color;
      });

And it seems OP is unaware in JS if you do

{} === {} // or use [] instead

this is false, because the references are compared.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading