JavaScript Array map()

JS
S
JavaScript

Simple examples of array.map() operations. Map() was added to ECMA-262 standard in the 5th edition (2011) https://www.ecma-international.org/ecma-262/5.1/ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

1/* ES2019 New Feature flatMap() */
2const names = ["John", "Johny", "Peter"]; 
3const mapOnly = names.map((name, idx) => [idx, name]); 
4const flatMap = names.flatMap((name, idx) => [idx, name]); 
5console.log(mapOnly); // [[0, “John”],[1, “Johny”],[2, “Peter”]] console.log(flatMap); // [0, “John”,1, “Johny”,2, “Peter”]
6
7
8// Apply a function to every element of the array. Map() is a functional construct, so a new array is returned and no mutation happens.
9
10const arr = [1,2,3,4];
11
12// Create a new array with doubles
13const doubleArray = arr.map((val,i,arr) => {
14  return val * 2;
15});
16
17// Create a new array with objects
18const objArray = doubleArray.map((val,i,arr) => {
19  return {
20    key: i,
21    value: val
22  }
23});
24
25// Create a new array, reformatting objects with even keys
26const evenKeysArray = objArray.map((val,i,arr) => {
27  if(val.key % 2 === 0){
28    val.value = val.value * 2;
29    return val;
30  } else {
31    return val;
32  }
33});
34
35// Split string and Count Characters
36const str = 'JavaScript';
37const strArray = Array.prototype.map.call(str,(element)=>{
38   return element;
39});
40console.log(strArray.length)
41
42
43// Iterare through a collection of objects and create a new clean array
44const collection = 
45[
46  {
47    "Samples":{
48      "Sample": [
49        {
50          "$":{
51            "name":"tester1",
52            "value":"tester2"
53          },          
54        },
55        {
56          "$":{
57            "name":"tester3",
58            "value":"tester4"
59          },          
60        }      
61      ]
62    },
63    "Experiences": {}
64  },
65  {
66    "Samples":{
67      "Sample": [
68        {
69          "$":{
70            "name":"tester5",
71            "value":"tester6"
72          },          
73        },
74        {
75          "$":{
76            "name":"tester7",
77            "value":"tester8"
78          },          
79        } 
80      ]
81    },
82    "Experiences": {}
83  },  
84]
85
86const cleanSamplesArray = [];
87
88const iterator = collection.map((outerObj,i,arr) => {
89  const samplesArray = outerObj.Samples.Sample;
90  samplesArray.map((val,j) =>{
91    const cleanSample = val.$;
92    cleanSamplesArray.push(cleanSample);
93    return cleanSample; // returning just for good practices as only 2nd object iteration will be returned
94  });
95});
96
97// Parse to integer
98function returnInt(element) {
99  return parseInt(element, 10); //parseInt requires 2 arguments
100}
101
102const numbers = ['2','3','5'];
103const parsedNumbers = numbers.map(returnInt);

Created on 11/23/2017