How to make your code faster using JavaScript Sets

If you only use arrays, you’re missing a trick

How are Sets different?

const arr = [A, B, C, D];console.log(arr.indexOf(A)); // Result: 0
console.log(arr.indexOf(C)); // Result: 2

What are the main benefits?

What is the time complexity?

Exactly how much faster are Sets?

Preparing the tests

let arr = [], set = new Set(), n = 1000000;for (let i = 0; i < n; i++) {
arr.push(i);
set.add(i);
}

Test 1: searching for an item

let result;console.time('Array'); 
result = arr.indexOf(123123) !== -1;
console.timeEnd('Array');
console.time('Set');
result = set.has(123123);
console.timeEnd('Set');

Test 2: adding an item

console.time('Array'); 
arr.push(n);
console.timeEnd('Array');
console.time('Set');
set.add(n);
console.timeEnd('Set');

Test 3: deleting an item

const deleteFromArr = (arr, item) => {
let index = arr.indexOf(item);
return index !== -1 && arr.splice(index, 1);
};
console.time('Array'); 
deleteFromArr(arr, n);
console.timeEnd('Array');
console.time('Set');
set.delete(n);
console.timeEnd('Set');

Case 1: removing duplicate values from an array

const duplicateCollection = ['A', 'B', 'B', 'C', 'D', 'B', 'C'];// If you want to turn the array into a Set
let uniqueCollection = new Set(duplicateCollection);
console.log(uniqueCollection) // Result: Set(4) {"A", "B", "C", "D"}
// If you want to keep your values in an array
let uniqueCollection = [...new Set(duplicateCollection)];
console.log(uniqueCollection) // Result: ["A", "B", "C", "D"]

Case 2: a Google interview question

Question

Solution

const findSum = (arr, val) => {
let searchValues = new Set();
searchValues.add(val - arr[0]);
for (let i = 1, length = arr.length; i < length; i++) {
let searchVal = val - arr[i];
if (searchValues.has(arr[i])) {
return true;
} else {
searchValues.add(searchVal);
}
};
return false;
};
const findSum = (arr, sum) =>
arr.some((set => n => set.has(n) || !set.add(sum - n))(new Set));

Writer and developer based in London. On Medium, I write about JavaScript and web development 💻

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store