How can I make an array true or false?

1.1k Views Asked by At

On Code.org, I'm trying to make a quiz that picks an answer based on what the user has placed in the array. However, regardless of what is in the array it always comes out false.

I've tried changing the statement to have more than one equal sign, I've tried doing it backward and making the if statement if list !== [list] and I've tried removing the quotations. Nothing has worked. I've also tried defining the correctlist variable inside the if statement, but that still produces false.

var mylist = ["a". "b", "c"];
var correctlist;

 if (mylist == ["a", "b", "c"]) {
  correctlist = true;
} else {
  correctlist = false;
}
console.log(correctlist);

It always comes out as false.

I expected the console log to state true but it always says false.

1

There are 1 best solutions below

0
On

You will notice that:["a", "b", "c"] == ["a", "b", "c"] always returns false.

That is because these are two different arrays. Just because the elements string match, the arrays are not the same.

You will either need to iterate through the elements to compare each, convert them to something that can be compared through a plain equality, or use a library with a "deep" equals.

JSON.stringify(["a", "b", "c"]) == JSON.stringify(["a", "b", "c"])