codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Learning JavaScript by Implementing Lodash Methods — Unzipping Arrays and Excluding Items

John Au-Yeung
codeburst
Published in
4 min readApr 28, 2020

--

Photo by Austin Distel on Unsplash

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at how to implement array methods for excluding items and unzipping arrays.

unzip

unzip accepts an array of grouped elements and creates an array by regrouping the elements into their configuration before zipping them.

All we have to do to implement unzip is to loop through each of the arrays and rearrange them as follows:

const unzip = (zipped) => {
let unzipped = zipped[0].map(z => []);
for (let j = 0; j < unzipped.length; j++) {
for (let i = 0; i < zipped.length; i++) {
unzipped[j].push(zipped[i][j])
}
}
return unzipped;
}

In the code above, we created a function that takes zipped arrays and inside the function, we mapped the first entry of zipped to a new array of arrays.

This is because the unzipped array should have arrays that are of the same size as each array entry in the zipped array.

Then we push the zipped entry in the given position into the unzipped array’s array entry.

For instance, if we call unzip with the following zipped array:

const result = unzip([
['a', 1, true],
['b', 2, false]
]);

Then unzip first maps the first zipped entry into a new array and set it to the unzipped variable.

Then the nested loop takes 'a' and then puts it into the first entry of the unzipped array. Then it pushes 'b' as the 2nd entry of the same array.

In the next iteration, it pushes 1 into the next unzipped array entry. Then it pushes 2.

The same process is done for the next iteration. Therefore, the unzipped array should be:

[
[
"a",
"b"
],
[
1,
2
],
[
true,
false
]
]

unzipWith

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet

Write a response