Skip to content

Instantly share code, notes, and snippets.

@nitish24p
Last active October 16, 2017 10:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitish24p/78d1cbfe53943e4c0e99fbb4e90baa96 to your computer and use it in GitHub Desktop.
Save nitish24p/78d1cbfe53943e4c0e99fbb4e90baa96 to your computer and use it in GitHub Desktop.
es6 Array immutable Array Actions

I have an array by the name students and a student object

let students = []

let student = {
  name: '',
  rollNumber: '',
  age: '',
  rank: ''
}

Following are immutable array Operations

1. adding an element to the array

  students.concat([student])

2. Deleting an object based on index from array

   var newStudentsArray = [...students.slice(0,index), ...students(index + 1)];

3. Deleting an object from the array based on some property

    var newStudentArray = students.filter((student) => student.rank < 5) 
   // will return a new array of all students whose rank is less than 5

###4. Updating a value of a particular object

   var newStudentArray = students.map((student) => {
    if(someProperty !== student.key) return student
    return Object.assign({}, student, NEW_OBJECT)
   })

or in Es6

   var newStudentArray = students.map((student) => {
    if(someProperty !== student.key) return student
    return {...student, NEW_OBJECT}
   })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment