DEV Community

Cover image for Mapping Arrays Like A Pro
Anurag Hazra
Anurag Hazra

Posted on • Edited on • Originally published at anuraghazra.github.io

Mapping Arrays Like A Pro

This post was originally published on my site.

Let's get started with some mapping. Previously I made a post about.
filtering arrays like a pro and this one also will be somewhat same, so put your seat belts on.

In this post, I will show you some cool tricks and hacks to map arrays.

To map arrays like a PRO we will use Array.prototype.map() method.

Mapping Number()

Using the Number object
we can convert any string of arrays to numbers easily.

['1', '2', '-1', '0'].map(Number);
// -> [1, 2, -1, 0]
Enter fullscreen mode Exit fullscreen mode

So, you might think that Number.parseInt will also work in this situation because it is also a function which we can pass into the map function, But no. See why:-

['1', '2', '-1', '0'].map(Number.parseInt);
// -> [1, NaN, -1, 0]
Enter fullscreen mode Exit fullscreen mode

It results in [1, NaN, -1, 0] because we mostly use parseInt with one argument, But it takes two, input & radix.

/**
 * @param {string} input
 * @param {number} radix
 */
parseInt('0011', 2)
// -> 3
Enter fullscreen mode Exit fullscreen mode

Thus when we pass parseInt to Array.prototype.map, it passes 3 arguments to the parseInt, the element, index & the array.

/*  1st iteration (index is 0): */ parseInt("1", 0);  // 1
/*  2nd iteration (index is 1): */ parseInt("2", 1);  // NaN
/*  3rd iteration (index is 2): */ parseInt("-1", 2); // -1
/*  4th iteration (index is 2): */ parseInt("0", 2);  // -1
Enter fullscreen mode Exit fullscreen mode

Checkout Mozilla Docs for better explaination of this

Mapping Object()

Well, this one is a bit of useless 😂, By passing the Object into map you can get the primitive value of the element.

let arr = ['1', '2', '-1', [1,3], {a : 1}, 0, null]
arr.map(Object)
// -> [String{"1"}, String{"2"}, String{"-1"}, [1, 3], {a: 1}, Number{0}, {}]
Enter fullscreen mode Exit fullscreen mode

You can also try this for fun.

Object.values(window).map(Object)
// OR
Object.values(window).map(String)
// OR
Object.values(window).map(Number)
// -> lot of things!
Enter fullscreen mode Exit fullscreen mode

Freezing Objects In An Array 🥶

By using the Object.freeze we can freeze all the objects inside the array.

let obj1 = { data: 'hello' };
let obj2 = { data: 'world' };
[obj1, obj2].map(Object.freeze)
Enter fullscreen mode Exit fullscreen mode

Mapping getOwnPropertyDescriptors()

Same as Object.freeze we can also pass Object.getOwnPropertyDescriptors to map all the propertyDescriptors.

[{a: 1}, {b: 2}].map(Object.getOwnPropertyDescriptors)
/* ->
[
  { a: { value: 1, writable: true, enumerable: true, configurable: true } },
  { b: { value: 2, writable: true, enumerable: true, configurable: true } }
]
*/
Enter fullscreen mode Exit fullscreen mode

Mapping CharCodes

Let's do some fun stuff :p

With the help of Array.fill() and String.fromCharCode method, we can map all the charCodes in an array.

new Array(100).fill(1).map(String.fromCharCode)
// -> This is soo weird that i can't even copy paste the output!
Enter fullscreen mode Exit fullscreen mode

Mapping Math

Let's also use map with the Math Object.

[0.2,1.5,-0.5,5,1,0,-0.8].map(Math.ceil)
// -> [1, 2, -0, 5, 1, 0, -0]
[0.2,1.5,-0.5,5,1,0,-0.8].map(Math.floor)
// -> [0, 1, -1, 5, 1, 0, -1]
[0.2,1.5,-0.5,5,1,0,-0.8].map(Math.abs)
// -> [0.2, 1.5, 0.5, 5, 1, 0, 0.8]
Enter fullscreen mode Exit fullscreen mode

You can also try to map other Math methods.

Mapping The Error Object

We can also directly map the Error Object.
Well, i don't know where will you find usefulness of this. 😂

['hello', 'world'].map(Error)
// -> [Error: hello at Array.map (<anonymous>) at <anonymous>:1:20, Error: world at Array.map (<anonymous>) at <anonymous>:1:20]
Enter fullscreen mode Exit fullscreen mode

Side Note

Same as my previous post about filtering arrays, you can also use those methods to map Boolean values into the array.

[undefined, null, 0, '', 'str', 2.5, 2, { a: 1 }, []].map(Boolean);
// -> [false, false, false, false, true, true, true, true, true]
[undefined, null, 0, 'str', 1, { a: 'b' }, [5, 6], [{ a: 5 }]].map(isArray)
// -> [false, false, false, false, false, false, true, true]
Enter fullscreen mode Exit fullscreen mode

That's it for this post, I hope you enjoyed these mapping tricks, and i know most of them are not very useful, But sometimes fun is what all you need.

hope you like this, and now you are also a PRO at mapping arrays! 😉.

And Don't forget to comment down your favorite array tricks and tips and let me know your thought's about these tricks. See ya!.

And also don't forget to checkout my other post:- filtering arrays like a pro

Cover Photo By T.H. Chia on Unsplash

Top comments (1)

Collapse
 
fetishlace profile image
fetishlace

Hi there:-) I think that that implicit argument passing to map function call is problem itself in any other case except when function is taking only one argument.
It sounds like parseInt is the problem, but that implicit passing of index is making confusion, since ['1', '2', '-1', '0'].map(x=>Number.parseInt(x)); is explicit, so more readable and working as intended here.
Then it leads to this part:
"With the help of Array.fill() and String.fromCharCode method, we can map all the charCodes in an array."
which is wrong or dirty or confusing at least, since we are not mapping array values = charCodes to strings, but we are doing String.fromCharCode(value, index, array) - so getting concat of strings String.fromCharCode(value) + String.fromCharCode(index) + String.fromCharCode(array) and that last array part is returning " ".
If it is saying we are mapping charCodes to strings (array values), it is not true.
new Array(100).fill(1).map(x=>String.fromCharCode(x)) is what was said.
Else i like playing with JS, just that middle part should be like base for the article about why to avoid implicit argument passing in map function:-)