DEV Community

Cover image for Immutability and you: Part 2
Alain D'Ettorre
Alain D'Ettorre

Posted on • Updated on

Immutability and you: Part 2

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',
]
*/
Enter fullscreen mode Exit fullscreen mode

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',
]
*/
Enter fullscreen mode Exit fullscreen mode

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',
]
*/
Enter fullscreen mode Exit fullscreen mode

Remove the first item (shift)

const countdown = [3, 2, 1];

const almostMidnight = countdown.slice(1);

/*
almostMidnight = [2, 1]
*/
Enter fullscreen mode Exit fullscreen mode

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']
*/
Enter fullscreen mode Exit fullscreen mode

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',
]
*/
Enter fullscreen mode Exit fullscreen mode

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',
];
*/
Enter fullscreen mode Exit fullscreen mode

Photo by Pietro Rampazzo on Unsplash

Discussion (0)