0

I am working quite a bit with Maps in javascript. I need the most computationally efficient way to find all items that are in Map a that are not present in Map b. For example,

const a = new Map();
a.set('item1', 'item1value');
a.set('item2', 'item2value');


const b = new Map();
b.set('item1', 'item1value');

The result of the function I'm looking to write would be another Map, with a single entry of key: item2, value: item2value.

I am well aware of the multitude of questions / answers / methods to do this with arrays and objects, however I have not seen such an explanation for maps. I need the absolute most efficient way to do so, as I will need to be call this function up to thousands of times quickly. Is conversion to an array and back to a Map the best way? Are there any tricks with Maps that may help?

23
  • do you need a symetrically difference? Dec 31, 2021 at 15:39
  • I don't think it matters in my case, as I'm pretty sure for my given scenario, Map b can never have entries not present in Map a, but Map a can have entries not present in Map b. Dec 31, 2021 at 15:41
  • 1
    If your values are always the same as the respective key, you shouldn't use a Map, you should use a Set! Then see 2ality.com/2015/01/es6-set-operations.html stackoverflow.com/q/31930894/1048572 stackoverflow.com/q/1723168/1048572
    – Bergi
    Dec 31, 2021 at 15:52
  • 2
    "as I will need to be call this function up to thousands of times quickly" ... that sounds like you should rethink your overall data model. Dec 31, 2021 at 16:13
  • 2
    Why do you need a copy "a thousand times"? This is a classic XY problem Dec 31, 2021 at 16:26

3 Answers 3

2

No, don't convert the maps to arrays and back. Computing the difference between arrays is slow, in a map you have O(1) lookup. Just loop through the entries of a and put them into the result if you don't find an equivalent entry in b. This will have the optimal time complexity O(n) (where n is the size of the map a).

const result = new Map();
for (const [k, v] of a) {
    if (v === undefined && !b.has(k) || b.get(k) !== v) {
        result.set(k, v);
    }
}

If you know that your map doesn't contain undefined values, you can omit the v === undefined && !b.has(k) || entirely and might get some speedup. Also, notice that if your map can contain NaN values, you'll want to use Object.is instead of ===.

If you want to write it as a single fancy expression, consider a generator:

const result = new Map(function*() {
    for (const e of a) {
        const [k, v] = e;
        if (v === undefined && !b.has(k) || b.get(k) !== v) {
            yield e;
        }
    }
}());
7
  • Thank you for this, this is the type of answer I was looking for. Some commenters mentioned looping over a and deleting entries that are also found in b. I didn't like that because I need to maintain a. This is more in line with what I need, as its additive rather than subtractive. Would you say there's a performance difference between an additive and subtractive approach? Dec 31, 2021 at 16:23
  • Well mutating the input doesn't need to allocate new memory for the result so can be faster, but if you need an immutable operation then you have no choice.
    – Bergi
    Dec 31, 2021 at 16:25
  • You can improve by avoiding the double lookup of both b.has() and b.get() for most items.
    – jfriend00
    Dec 31, 2021 at 16:52
  • @jfriend00 That's what my second paragraph says. Or do you mean I should write !(v === undefined && b.has(k)) || b.get(k) !== v?
    – Bergi
    Dec 31, 2021 at 16:53
  • 1
    @SethLutske It'll be O(size(a) + size(b)), whereas my approach is O(size(a)). So unless b is significantly smaller than a, and unless copying the map all-at-once is faster than copying it one-at-a-time (maybe because of special-cased memory allocation?), I doubt it's faster. But really, you should just race your horses.
    – Bergi
    Dec 31, 2021 at 17:06
1

You could iterate the first map and check against the second.

const
    a = new Map([['item1', 'item1'], ['item2', 'item2']]),
    b = new Map([['item1', 'item1']]),
    difference = (a, b) => {
        const d = new Map;

        a.forEach((v, k) => {
            if (!b.has(k) || b.get(k) !== v) d.set(v, k);
        });
        return d;
    }

console.log([...difference(a, b)])

6
  • I thought of something like this, I just wasn't sure if a for loop was going to be the most efficient way to do it. Any thoughts on this method's cpu impact? Dec 31, 2021 at 15:49
  • This can be improved by not doing both b.has() and b.get(). That's double lookup. You only have to do the double lookup if b.get() returns undefined.
    – jfriend00
    Dec 31, 2021 at 16:22
  • I think you messed up the condition. Your snippet results in an empty map but shouldn't.
    – Bergi
    Dec 31, 2021 at 16:26
  • @jfriend00 a proper JIT compiler will eliminate the second lookup. Dec 31, 2021 at 16:30
  • sorry, please see edit. Dec 31, 2021 at 16:47
0

Perhaps like this by maintaining a;

var a = new Map(),
    b = new Map(),
    c;

a.set('item1', 'item1value');
a.set('item2', 'item2value');
b.set('item1', 'item1value');

c = new Map(a);
b.forEach((_,k) => c.delete(k));

console.log(c); // try in dev tools to see result

4
  • Thank you for this. Would you mind explaining this method's effect on cpu usage? One of the commenters mentioned this method doesn't allocate any heap memory, which sounds good, though I'm not sure why, or how this method differs from the additive method in Bergi's answer. Mind elaborating a bit? Dec 31, 2021 at 16:25
  • 1
    According to the OP's comments on the question, you should delete entries in c only if they also have the same value, not just the same key
    – Bergi
    Dec 31, 2021 at 16:28
  • @Bergi Couldn't elaborate what you say from the question. If that's required than one might try b.forEach((v,k) => c.has(k) && (c.get(k) === v) && c.delete(k)); guaranteeing possible keys with undefined values to be deleted.
    – Redu
    Dec 31, 2021 at 16:41
  • @SethLutske Sorry no, i can not. It might be helpful to set up a benchmark run at one of the online suits like jsben.ch, jsbench.me or Perflink and post the results here.
    – Redu
    Dec 31, 2021 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.