1

Let's say I had an array containing unique values, and I wanted to check if a certain element existed:

var bannedIPs = ['0.0.0.0', '127.0.0.1', '192.168.1.1', '192.168.1.2'];
var isBanned = bannedIPs.includes('0.0.0.0'); // true

This works fine, except for the fact that it uses linear search, meaning that for an array of N elements, it would take N iterations to check if an element existed.

A much faster way to do this would be to use an object:

var bannedIPs = {'0.0.0.0': null, '127.0.0.1': null, '192.168.1.1': null, '192.168.1.2': null};
var isBanned = bannedIPs.hasOwnProperty('0.0.0.0'); // true

This method uses O(1) lookup, which is done in constant time, leading to much better performance.

However, notice how I have to store arbitrary values for the keys. Is there any other method that is potentially more suitable for this task, one that maybe doesn't require you to store values for each key?

2 Answers 2

3

Use a Set instead. Unlike an array, and unlike an object, and unlike a Map, Sets are collections of just plain values, without any associated key.

var bannedIPs = new Set(['0.0.0.0', '127.0.0.1', '192.168.1.1', '192.168.1.2']);
var isBanned = bannedIPs.has('0.0.0.0'); // true
Sign up to request clarification or add additional context in comments.

1 Comment

The initial construction of N items in a Set is O(n), but subsequent additions/deletions/lookups in that Set is either O(1) or at least sublinear.
2

You can use a Set.

var bannedIPs = new Set(['0.0.0.0', '127.0.0.1', '192.168.1.1', '192.168.1.2']);
var isBanned = bannedIPs.has('0.0.0.0');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.