Last active
May 25, 2016 14:38
-
-
Save proclaim/824dc20c7538da5bb2d6056bbc667adc to your computer and use it in GitHub Desktop.
Add / remove item from array without mutaiton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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