-3

Let's say I have an array containing multiple dictionaries like so :

var coords = [{'x': 0, 'y': 0}, {'x': 2, 'y': 5}, {'x': 1, 'y': 6}]

And I try to run a array.includes on it, it simply doesn't work :

console.log( coords.includes({'x': 0, 'y': 0}) )
// Output : false

It only does this when I work with an array containing dictionaries. For example this works just fine :

var coords = ['0-0', '2-5', '1-6']
console.log( coords.includes('0-0') )
// Output : true

Is there a reason for this? And would there be a way to make it work with dictionaries?

Tiger
  • 53
  • 9

1 Answers1

0

You can use JSON.stringify() to search for dictionaries in an array.

We can first use map() on the array and convert all of the elements to JSON strings.

const coords = [{'x': 0, 'y': 0}, {'x': 2, 'y': 5}, {'x': 1, 'y': 6}]
.map(elm => JSON.stringify(elm));

After doing that, searching is pretty straightforward.

const target = {'x': 0, 'y': 0}; // object you're searching for
console.log(coords.includes(JSON.stringify(target))); // true

This works because you're are now comparing strings (output from JSON.string()) instead of comparing objects (which is just comparing object references instead of the contents).

NerdyGamer
  • 104
  • 1
  • 4