Skip to content

Instantly share code, notes, and snippets.

@pankajladhar
Last active June 20, 2018 22:23
Show Gist options
  • Save pankajladhar/ea915ce59033ac4078a0cb96206f842c to your computer and use it in GitHub Desktop.
Save pankajladhar/ea915ce59033ac4078a0cb96206f842c to your computer and use it in GitHub Desktop.
ES6 Cheatsheet

Usage of Reduce method

const posts = [
    {id: 1, upVotes: 2},
    {id: 2, upVotes: 89},
    {id: 3, upVotes: 1}
];

const totalUpVotes = posts.reduce((acc, curr)=>{
    return acc + curr.upVotes
}, 0)

console.log(totalUpVotes) // 92

Usage of Map method

const users = [
    {id: 1, name: "Foo"},
    {id: 2, name: "Bar"},
    {id: 3, name: "FooBar"}
];

const mappedUser = users.map((user)=>{
    return {
        id : user.id + 100,
        name: user.name
    }
});

console.log(mappedUser) // [ {id: 101, name: "Foo"}, {id: 102, name: "Bar"}, {id: 103, name: "FooBar"}];

Usage of filter method

const users = [
    {id: 1, name: "Foo", isActive: true},
    {id: 2, name: "Bar", isActive: false},
    {id: 3, name: "FooBar", isActive: true}
];

const activeUsers = users.filter((user)=>{
    return user.isActive
})

console.log(activeUsers) // [{"id":1,"name":"Foo","isActive":true},{"id":3,"name":"FooBar","isActive":true}]​​​​​

Adding an element to an array of objects

const users = [
    {id: 1, name: "Foo"},
    {id: 2, name: "Bar"}
];

const newUsers = [...users, { id: 3, name: "FooBar" }]

console.log(newUsers) // [{"id":1,"name":"Foo"},{"id":2,"name":"Bar"},{"id":3,"name":"FooBar"}]​​​​​

Adding a key value pair to an object

const users =  {id: 1, name: "Foo"};

const newUsers = {...users, isActive: true}

console.log(newUsers) // {"id":1,"name":"Foo", isActive: true}

Adding a key value pair with dynamic key

const dynamicKey = "hasSmartPhone";

const users =  {id: 1, name: "Foo"};

const newUsers = {...users, [dynamicKey]: false}

console.log(newUsers) // {"id":1,"name":"Foo", hasSmartPhone: true}

Find and replace key value pair in array of objects

const posts = [
    {id: 1, title: 'Title 1'},
    {id: 2, title: 'Title 2'}
];

const updatedPost = posts.map((post)=>{
    return post.id === 1 ? {...post , title : "Updated Title 1"} : post
})

console.log(updatedPost) // [{"id":1,"title":"Updated Title 1"},{"id":2,"title":"Title 2"}]​​​​​

Find an element inside an array of objects

const posts = [
    {id: 1, title: 'Title 1'},
    {id: 2, title: 'Title 2'}
];

const postInQuestion = posts.find(p => p.id === 2);

console.log(JSON.stringify(postInQuestion)) // {id: 2, title: 'Title 2'}

Delete a key value pair inside an object

const users = {id: 1, name: 'foo', password: "foo@123"};

const userWithoutPassword = (({ id, name } )=>{
    return({ id, name }) //{ id : id, name: name }
})(users)

console.log(userWithoutPassword) // {id: 1, name: 'foo'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment