-2

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?

2
  • in javascript {'x': 0, 'y': 0} != {'x': 0, 'y': 0} so, you'll need to do coords.find instead Commented Aug 30, 2023 at 1:52
  • so, you'll need to do coords.some() instead Commented Aug 30, 2023 at 1:56

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.