Skip to content

Instantly share code, notes, and snippets.

@proclaim
Last active May 25, 2016 14:38
Show Gist options
  • Save proclaim/824dc20c7538da5bb2d6056bbc667adc to your computer and use it in GitHub Desktop.
Save proclaim/824dc20c7538da5bb2d6056bbc667adc to your computer and use it in GitHub Desktop.
Add / remove item from array without mutaiton
const students = ['yoshie', 'hiroshie', 'lisa', 'johnny'];
const removeStudent = (students, index) => {
return [
...students.slice(0, index),
...students.slice(index + 1)
]
}
const addStudent = (students, index, newStudent) => {
return [
...students.slice(0, index),
newStudent,
...students.slice(index)
]
}
console.log(addStudent(students, 2, 'arima')); // ["yoshie", "hiroshie", "arima", "lisa", "johnny"]
console.log(students); // ["yoshie", "hiroshie", "lisa", "johnny"]
console.log(removeStudent(students, 1)); // ["yoshie", "lisa", "johnny"]
console.log(students); // ["yoshie", "hiroshie", "lisa", "johnny"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment