From e40175d8d1ce04c33691137a4ee94af5353c7f60 Mon Sep 17 00:00:00 2001 From: Jo Wroten Date: Tue, 9 Jul 2019 20:32:22 +0000 Subject: [PATCH] =?UTF-8?q?Update=20Posts=20=E2=80=9Cusing-js-sets-to-find?= =?UTF-8?q?-elements=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../posts/using-js-sets-to-find-elements.md | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/content/posts/using-js-sets-to-find-elements.md b/content/posts/using-js-sets-to-find-elements.md index 13fd937..51fabdf 100644 --- a/content/posts/using-js-sets-to-find-elements.md +++ b/content/posts/using-js-sets-to-find-elements.md @@ -8,7 +8,23 @@ description: >- loops. - https://gitlab.com/snippets/1873655 + ```js + + // Example Data + + let hugeArray = [...Array(10000).keys()].map(id => { return {id}; }); // [{id: + 0}, ..., {id: 9999}] + + let needles = [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]; + + + // Finding matching elements + + let needlesSet = new Set(needles); + + let matches = hugeArray.filter(obj => needlesSet.has(obj.id)); + + ``` --- Functionally for one check, this is identical to checking the `.indexOf()` or `.includes()` of an Array. However, in cases where you're filtering a large array down to match a list of ID's, for example, the nested looping can result in a performance hit. Traditionally hash tables were used for speeding up this search, but with ES2015 we can now leverage Sets which are easier to read and still result in a single loop that's equal to the length of the Array and no more. (Can be further optimized by ending when running out of needles) @@ -21,3 +37,5 @@ let needles = [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]; let needlesSet = new Set(needles); let matches = hugeArray.filter(obj => needlesSet.has(obj.id)); ``` + +https://gitlab.com/snippets/1873655