All things Software Dev & Architecture

All things Software Dev & Architecture

Functional Array management with ES6

@thebarefootdev's JavaScript tips

Subscribe to my newsletter and never miss my upcoming articles

With ES6 syntax, working with arrays has never been easier. The spread operator in particular allows a much cleaner and functional approach, to adding, updating and removing items in an array without the previous hassle of looping, or the need to use pushing or popping!

Enjoy!

// USING AN ARRAY OF PRIMITIVES
let items = ["apples","oranges","pears"];

const add = (arr, item) =>[...arr, item]
const remove = (arr, itemId) => arr.filter(i => i.id !== itemId)

items = add(items, "bananas"); 
console.log(items); // ["apples","oranges","pears","bananas"]

items = remove(items, "oranges"); 
console.log(items); // ["apples","pears","bananas"]

/*********************************************************/

// USING AN ARAY OF OBJECTS
let users = [{id: 1, name: "John Smith"}];

const _printUsers = _users => {
    let str = "";
    for (let u of _users){
        str += u.name + ", "
    }
    console.log(str)
};

printUsers(users); // John Smith,

const addUser = (_users, user) => [..._users, user];
const removeUser = (users, userId) => users.filter(u => u.id !== userId);
const updateUser = (users, user) => [...removeUser(users, user.id), user];

const newUser = {id: users.length +1, name: "Jane Doe"};
users = addUser(users, newUser);
_printUsers(users) // John Smith, Jane Doe,

const updatedUser = {...newUser, name: "Jane Smith"};
users = updateUser(users, updatedUser);
_printUsers(users); // John Smith, Jane Smith,

users = removeUser(users, newUser.id)
_printUsers(users); // John Smith,
 
Share this