Created
November 10, 2018 05:15
-
-
Save iHani/94f80cf5a926659011ac4d8754f18252 to your computer and use it in GitHub Desktop.
array.map() examples- JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "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