Thinking Beyond For & Nested loop :- Part 2

Vikash Agarwal
Frontend Weekly
Published in
3 min readJul 7, 2020
https://unsplash.com/photos/KQ0C6WtEGlo

Check Part 1 here

As we create more complex code on the front end and use Array a lot, one thing I see missing from most of the developers to think beyond the usage of Array. There are other data structures available such as Map, Set etc… which can be used to write clean code. Just like Array, Map & Set are first class citizen in JavaScript now.

I feel many developers are stuck using array for each and everything related to the collection of values. This often leads to nested loops increasing the complexity.

In this article, I will show how to use array with other structures to keep code clean.

Set is used keep list of unique values.

Example :- keeping array of unique values :- Using Set

//Finding unique values:- using .forEach loop without using setfunction unique(arr){
const resultArray = [];
arr.forEach(num => {
if (resultArray.indexOf(num) === -1){
resultArray.push(num);
}
});
return resultArray;
}
unique([1,2,4,3,2,1,4,4,1]) will return [1,2,4,3];

Above code is really common among many developers who keeps array as their main choice for all the list related task. When it comes to unique values, Set is preferred data structure. And luckily now it’s available in javascript as well. Above code can be simplified by just using Set

//Finding unique values:- using Set Ex1function unique(arr){const set = new Set();  
arr.forEach(num => {
set.add(num);
});
return [...set];
}
//Finding unique values:- using Set Ex2 (one liner)function unique(arr){
return [...new Set(arr)];
}
unique([1,2,4,3,2,1,4,4,1]) will return [1,2,4,3];

About Set

  • Contains only unique values
  • Can take array as input. It only keeps unique values and remove duplicate ones
  • Has inbuilt iterator to iterate the values.

understanding the one liner example,

  • new Set(arr) :- creates a set object with array as input.
  • […] :- creates new array with the values returned by the set’s iterator.

Set comes very handy if you want to work with unique values scenario. You can take advantage of it only if you know about this concept.

Map is used to store key, value pairs where key can be primitive/non primitive.

Example :- Merging two arrays :- Using Map

//Example :- Merging promotion list with the actual product listGiven 2 array, one having list of products and one having promotion information. We need to merge products array with the promotion array to calculate the discounted price.const products = [
{ "id":"1", "title":"Sweet fresh strawberry", "price":29.45},
{ "id":"2", "title":"Asparagus", "price":18.95},
{ "id":"3", "title":"Green smoothie", "price":17.68},
{ "id":"4", "title":"Raw legumes", "price":17.11},
{ "id":"5", "title":"Brown eggs", "price":28.1}
]
const promotions = [
{ "productId":"2", "title":"Asparagus", "discount":2.95},
{ "productId":"5", "title":"Brown eggs", "discount":3.1}
]

for the above usecase or similar usecases, below solution is a very common approach.

//Common Solution. using nested loopfunction merge(productArr, promotionArr){
productArr.forEach(product => {
let appliedPromotion;
promotionArr.forEach(promotion => {
if (promotion.productId === product.id){
appliedPromotion = promotion;
}
})
if (appliedPromotion){
product.price = product.price - appliedPromotion.discount;
}
})
}

Let’s look at a different solution.

//Solution using mapfunction merge(productArr, promotionArr){

//Step1. creating map of promotion.
const promotionMap = promotionArr.reduce((promotionMap, promotion) => {
promotionMap.set(promotion.productId, promotion);
return promotionMap;
}, new Map());
//loop all product and check in the map if promotion is available.
productArr
.filter(product => promotionMap.has(product.id))
.forEach(product => {
product.price -= promotionMap.get(product.id).discount;
})
}

In the above solution, there is no nested loop plus the logic is very clean.

if your key is primitive then you can use simple object as a map which should be faster than map.get().

About Map

  • Map provides set, get, has method along with several other handy functions.
  • You can use object as key.
  • Can take [key, value] pair array as input.
  • Has inbuilt iterator to iterate the values.

Along with Set and Map, it will be really good to go through other related concepts such as WeakMap, WeakSet under KeyedCollection.

Check Part1 here

Related story below

--

--