var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; var result = arr1.concat(arr2);
We can achieve the same thing by using the spread operator. The spread operator is represented by three dots/periods (...). To concatenate two arrays we first create a new array by using two square brackets, then the first element we use the spread operator on the first array and we do the same with the 2nd element and 2nd array. The spread operator will expand the arrays into there elements. So the 'result' variable will contain the number 1 through 10, as before.
var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; var result = [...arr1, ...arr2];
If we didn't use the spread operator, as shown below. The 'result' array would contain two arrays, inside of 10 numbers. The first element would contain an array/list of the number 1 through 5 and the second element will be another list with the number 6 through 10.
var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; var result = [arr1, arr2];
You can also combine raw values and a spread operator to create a new array. The below result variable will contains a list of number from -2 to 5. This is because we are adding the raw value -2, -1, and 0 and then concatenating the 'arr1' list using a spread operator.
var arr1 = [1, 2, 3, 4, 5]; var result = [-2, -1, 0, ...arr1];
You can also use array methods, such as the filter function, in combination with the spread operator to create really custom lists. The below 'result' variable will contain a list of number from 3 to 6. Without the spread operator the result variable would contain two arrays instead of a list of just numbers.
var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; var result = [...arr1.filter(i => i > 2), ...arr2.filter(i => i < 7)];
This post was originally published on https://acroynon.com
A career in tech is fun, makes you a better thinker, keeps you mentally young, gives you a passport to companies everywhere in the world, keeps you challenged, is not going to be automated out of existence, pays well and is compatible with whatever passions you might have.