peterschussheim
10/13/2016 - 3:47 PM

map

map

const names = ["Peter", "Nick", "Dagniel"]; ///convert an array of elements to an array of objects, with each object containing a 'firstname' prop that is mapped to the names[i] value.
const mapped = names.map(function(name) {
    return {
        firstname: name
    }
})

mapped
///Map creates a new array that is the SAME length as the original. Uses the return value to build up the new array.
const integers = ["1", "2", "3", "4", "5"];

const mapped = integers.map(x => Number(x));
///Pull only active users.
const items = [
    {
        active: true,
        firstName: 'Peter', ///add an \`active\` prop to each person.
        lastName: 'Schussheim'
    },
    {
        active: true,
    	firstName: 'Nicky',
        lastName: 'Cat'
    },
    {
        active: false,
    	firstName: 'Badger',
        lastName: 'Cat'
    }
];

const mapped = items
	.filter(x => x.active)
	.map(x => x.firstName);

function createLi(items) {
    const listElements = items.map(x => `  <li>${x}</li>`).join('\n');
    return `<ul>\n${listElements}\n</ul>`;
}
///Take an array of objects and pull off a particular value from each object.
const people = [
    {
        firstName: 'Peter',
        lastName: 'Schussheim'
    },
    {
        firstName: 'Nicky',
        lastName: 'Cat'
    }
];

var items = ["Binky", "Kevin"];
function createLi(items) {
    const listElements = items.map(x => `  <li>${x}</li>`).join('\n');
    return `<ul>\n${listElements}\n</ul>`;
}

var list = createLi(items);

const mapped = people.map(x => x.firstName);
///Add fields onto objects to better suite a particular application.
const people = [
    {
        firstName: 'Peter',
        lastName: 'Schussheim'
    },
    {
        firstName: 'Nicky',
        lastName: 'Cat'
    }
];

const mapped = people.map(x => {
    return {
        firstName: x.firstName,
        lastName: x.lastName,
        fullName: x.firstName + ' ' + x.lastName
    };
});

map

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.