Skip to content

Instantly share code, notes, and snippets.

@aluksidadi
Last active February 19, 2024 16:05
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aluksidadi/10aa07c6f007efc587f793212548ad51 to your computer and use it in GitHub Desktop.
Save aluksidadi/10aa07c6f007efc587f793212548ad51 to your computer and use it in GitHub Desktop.
Immutable javascript using es6 cheatsheet

Object

Merge object / Object assign / Object extend

const obj1 = {a: 1, b: 2, c: 3};
const obj2 = {c: 4, d: 5};

const obj3 = {
  ...obj1,
  ...obj2,
};
// obj3 === {a: 1, b:2, c:4, d: 5}

Updating object

const obj1 = {a: 1, b:2 , c: 3};
const a = 4;
const c = 5;

const updatedObj1 = {
  ...obj1,
  a,
  c,
};
// updatedObj1 === {a: 4, b:2, c: 5}

Array

Append item into array

const arr = [0,1,2,3];
const newItem = 4;

const updatedArr = [
  ...arr,
  newItem,
];
// updatedArr = [0,1,2,3,4];

Prepend item into array (Unshift)

const arr = [1,2,3,4];
const newItem = 0;

const updatedArr = [
  newItem,
  ...arr,
];
// updatedArr = [0,1,2,3,4];

Add array item in between

const arr = [0,1,2,3,4,5];

const indexToAdd = 3;
const itemToAdd = 6;
const updatedArr = [
  ...arr.slice(0, indexToAdd),
  itemToAdd,
  ...arr.slice(indexToAdd + 1),
];
// updatedArr === [0,1,2,6,3,4,5];

Concat / merge array

const arr1 = [0,1,2];
const arr2 = [3,4,5];

const mergedArr = [
  ...arr1,
  ...arr2,
];
// mergedArr === [0,1,2,3,4,5]

Remove array item

const arr = [0,1,2,3,4];

const indexToRemove = 3;
const updatedArr = [
  ...arr.slice(0, indexToRemove),
  ...arr.slice(indexToRemove + 1),
];
// updatedArr === [0,1,2,4]
@anvk
Copy link

anvk commented Apr 19, 2017

Another good pure-functional operations

Removal and add item into array of objects:

const arr = [
  {
    id: 1,
    name: 'Alex N'
  },
  {
    id: 2,
    name: 'Alex L'
  },
];

const updatedItem = {
  id: 1,
  name: 'Alex Novak',
};

const updatedArr = updatedArr.map((item) => {
  if (item.id !== updatedItem.id) {
    return item;
  }

  return {...item, ...updatedItem};
});
const arr = [
  {
    id: 1,
    name: 'Alex N'
  },
  {
    id: 2,
    name: 'Alex L'
  },
];

const removedId = 1;

const updatedArr = updatedArr.filter(item => item.id !== removedId);

@anvk
Copy link

anvk commented Apr 19, 2017

And another one. Updating an object:

let state = {
  id: 1,
  name: 'Alex N',
};

const newName = 'Alex Novak';

state = {
  ...state,
  name: newName,
};

@anvk
Copy link

anvk commented Apr 19, 2017

And updating an object within the object:

let state = {
  id: 1,
  name: 'Alex N',
  job: {
    name: 'developer',
    grade: 'awesome',
  }
};

const newGrade = 'More Awesome!';

state = {
  ...state,
  job: {
    ...state.job,
    grade: newGrade,
  },
};

@aluksidadi
Copy link
Author

Thanks for the contribution @anvk!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment