1

I created a Set of 2D arrays like this:

let set = new Set([[1, 2], [4, 6]]);

now when I am doing set.has([1, 2]) it returns false. How can I achieve this?

Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30

1 Answers1

4

If you're going to compare objects or arrays (which aren't primitives, and so aren't ===), stringify everything in the Set first:

const set = new Set([[1, 2], [4, 6]]);
const setStringified = new Set([...set].map(JSON.stringify));

console.log(setStringified.has(JSON.stringify([1, 2])));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    If there's just one item being compared, yeah, there's not much point in creating another Set (using `.some` instead would work instead), but if there are multiple items to check, the Set has less computational complexity – CertainPerformance May 26 '19 at 09:02
  • arrays have an order, sets don't. – Nina Scholz May 26 '19 at 09:04
  • @NinaScholz - Yes they do. The order of entries in a Set is the order they were added. The [[SetData]] in a set is a *list* which is appended to when you add a new value. This is also covered by *"... in original insertion order..."* in Set's [`forEach`](https://tc39.github.io/ecma262/#sec-set.prototype.foreach). The iterator works by index into [[SetData]], so that's also insertion order (provided you don't modify the set during iteration, which gets ugly because the iterator works by index). – T.J. Crowder May 26 '19 at 09:12
  • @T.J.Crowder, i know, but `[1, 2, 2]` is as array different, by looking at the values from `[2, 1, 1]`. by taking a set for the values, both are equal. – Nina Scholz May 26 '19 at 09:15
  • @NinaScholz - I don't think the above does that. It converts the set `[[1, 2], [4, 6]]` into the set `["[1,2]", "[4,6]"]` and then uses `has` on `"[1,2]"`. It's not going to confuse `"[2,1]"` for `"[1,2]"`. – T.J. Crowder May 26 '19 at 09:19