#js2019
Explore tagged Tumblr posts
Text
Array Insertions With The Spread Operator
The spread operator ... helps make array operations much easier by removing method calls like concat and other management. For example, to combine two arrays and add a value into the middle of them with concat without mutating the arrays:
function insertInMiddle(array1, value, array2) { return array1.concat(value).concat(array2); } const arr1 = [1, 2, 3]; const arr2 = [5, 6, 7]; console.log(insertInMiddle(arr1, 4, arr2)); // [ 1, 2, 3, 4, 5, 6, 7 ] console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 5, 6, 7 ]
That is not too bad, but will quickly become hard to manage if more array operations are done. Instead that can all be put in one array return with no extra methods:
function insertInMiddle2(array1, value, array2) { return [...array1, value, ...array2]; } console.log(insertInMiddle2(arr1, 4, arr2)); // [ 1, 2, 3, 4, 5, 6, 7 ] console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 5, 6, 7 ]
It also appears the spread at least in some cases is faster than concat with arrays: https://jsperf.com/spread-vs-concat-vs-push
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/spreadArrayAdditions.js
#arrays#spread#es6#js2019#js#nodejs#immutability#javascript#programming#web development#app development
5 notes
·
View notes