Immutability and you: Part 2
Alain D'Ettorre
Posted on July 9, 2020
In this article we're going to see how you can change an array immutably
Add new values at the end (push)
const boringSuperpowers = [
'X-ray vision',
'Invisibility',
'Super strength',
];
const yourSuperpowers = [
...boringSuperpowers,
'Programming in JavaScript',
'Using immutability',
];
/*
yourSuperpowers = [
'X-ray vision',
'Invisibility',
'Super strength',
'Programming in JavaScript',
'Using immutability',
]
*/
Add new values at the beginning (unshift)
const starWarsBefore2000 = [
'A New Hope',
'The Empire Striked Back',
'Return of the Jedi',
];
const starWarsAfter2000 = [
'The Phantom Menace',
'Attack of the Clones',
'Revenge of the Sith',
...starWarsBefore2000,
];
/*
starWarsAfter2000 = [
'The Phantom Menace',
'Attack of the Clones',
'Revenge of the Sith',
'A New Hope',
'The Empire Striked Back',
'Return of the Jedi',
]
*/
Remove the last item (pop)
const week = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
];
const weekIdLike = week.slice(0, week.length - 1);
/*
weekIdLike = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
]
*/
Remove the first item (shift)
const countdown = [3, 2, 1];
const almostMidnight = countdown.slice(1);
/*
almostMidnight = [2, 1]
*/
Replace an item inside an array
const starters = [
'Bulbasaur',
'Squirtle',
'Charmander',
];
const sorrySquirtle = [
...starters.slice(0, 1),
'Rattata',
...starters.slice(2),
];
/*
sorrySquirtle = ['Bulbasaur', 'Rattata', 'Charmander']
*/
Remove an item inside an array
Note: You can remove any portion of the array with this technique, not just a single item
const pickACard = [
'Queen of Hearts',
'Ace of Spades',
'2 of Pikes',
];
const remainingCards = [
...pickACard.slice(0, 1),
...pickACard.slice(2),
];
/*
remainingCards = [
'Queen of Hearts',
'2 of Pikes',
]
*/
Sort and/or reverse an array
const people = [
'Bob',
'Alice',
'Charlie',
];
const sorted = [...people].sort();
const reverseSorted = [...sorted].reverse();
/*
sorted = [
'Alice',
'Bob',
'Charlie',
];
reverseSorted = [
'Charlie',
'Bob',
'Alice',
];
*/
Photo by Pietro Rampazzo on Unsplash
π πͺ π
π©
Alain D'Ettorre
Posted on July 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.