Insert an array in the middle of another array with ES6 Spread
This video covers stepwise approach on how to insert an array in the middle of an existing array using Spread Element in ES6.
/*** Goal: Insert english2Gpa in the middle of english1Gpa*/let english1Gpa = [2.3, 2.80, 2.82];let english2Gpa = [2.42, 2.47, 2.77];let middleIndex = Math.floor(english1Gpa.length/2);english1Gpa.splice(middleIndex, 0, ...english2Gpa);console.log(english1Gpa);
2:29 And you will see that newScores now have all the elements from scores. So let's now stitch all these pieces together to solve our problem. Alright, so time to write the code on the editor. We have two arrays already here. We are going to find the middle index of english1Gpa array now. To find the middle index, we are going to name a variable middleIndex and we will use math.floor as we saw previously and we will pass as argument english1Gpa length and that has to be divided by two because we need to find middle index. Once we have the middleIndex, now we are going to splice the english1Gpa array. During splicing, we need to pass the first argument as start index, which is going to be the middleIndex. We want to start inserting the elements from this index onwards.
3:15 Zero is the count and we are going to spread english2Gpa array. Now spread expands all the elements that were in english2Gpa array right here. Now it's time to log the value of english1Gpa array because we spliced it, we will do console.log english1Gpa. Alright, so let's run the program and see what the result is. If you notice splice did change the original array, but we were able to insert english2Gpa array starting from the middle index. So I hope you got the idea how to make use of math.floor to find the middle index. Then then splicing the array and finally using the spread element open up the elements inside the array. I hope this small session was helpful for you. Thanks for watching. And if you have any questions, drop the comments. You may want to subscribe to this channel if you want to learn fast with these short videos. Until then, my friends keep learning and share your knowledge.