Skip to content

Instantly share code, notes, and snippets.

@iHani
Created November 10, 2018 05:15
Show Gist options
  • Save iHani/94f80cf5a926659011ac4d8754f18252 to your computer and use it in GitHub Desktop.
Save iHani/94f80cf5a926659011ac4d8754f18252 to your computer and use it in GitHub Desktop.
array.map() examples- JavaScript
// "The map() method creates a new array with the results of calling a provided function on every element in the calling array." - MDN
// .map() returns an array of the same length, don't use it for filtering, use .filter() insted
/* example 1 */
const fruits = [ 'orange', 'apple', 'pineapple' ];
// maps are good for 'applying' something on every element in the array, let's apply .toUpperCase()
const fruitsUppercase = fruits.map(fruit => fruit.toUpperCase());
console.log(fruitsUppercase);
// [ 'ORANGE', 'APPLE', 'PINEAPPLE' ]
console.log(fruits); // original array does not change because we used it in a variable
// [ 'orange', 'apple', 'pineapple' ]
/* example 2 */
const people = [
{ id: 1, age: 20 },
{ id: 2, age: 50 },
{ id: 3, age: 11 }
];
// Let's add a property called "canDrive" to those people based on their age
people.map(person => person.canDrive = (person.age > 16));
console.log(people); // orignal array changes because we applied map() directly
// [ { id: 1, age: 20, canDrive: true },
// { id: 2, age: 50, canDrive: true },
// { id: 3, age: 11, canDrive: false } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment