Let's assume that we have the following array and we want to complete it:
javascriptlet numbers = [1, 2, 3, 4, 6, 7];
Since the number 5 is missing, we want to insert it between 4 and 6. We can slice the array in two parts and then use the spread operator ...
to put everything together again:
javascript// We are slicing the array in two parts: 0 - 4 and 4 - End let first = numbers.slice(0, 4); let second = numbers.slice(4); // We insert number 5 between those two parts let completed = [...first, 5, ...second]; // [1, 2, 3, 4, 5, 6, 7]
In one line of code:
javascriptlet completed = [...numbers.slice(0, 4), 5, ...numbers.slice(4)]; // [1, 2, 3, 4, 5, 6, 7]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.