Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Happy Tuesday daily_programmer!
- Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3]
- Please DM me with ideas for future problems. When you have completed it post a link to your solution.
- *if you have a question about someones solution please use a thread under their posted link*
- */
- // alternate and combine arrays
- function altCombineArrays(firstArray, secondArray) {
- // set up our result variable
- var result = [];
- // set up our length variable
- var length = 0;
- // see which array is longer and set that as our length
- if (firstArray.length > secondArray.length) {
- length = firstArray.length;
- } else {
- length = secondArray.length;
- }
- // run our for loop the length of our longest array
- for (var i = 0; i < length; i++) {
- // only push from first array if we still have a value
- if (i < firstArray.length) {
- result.push(firstArray[i]);
- }
- // only push from second array if we still have a value
- if (i < secondArray.length) {
- result.push(secondArray[i]);
- }
- }
- // return our result
- return result;
- }
- var arrayOne = ['a', 'b', 'c', 'd', 'e'];
- var arrayTwo = [1, 2, 3, 4, 5, 6, 7, 8];
- altCombineArrays(arrayOne, arrayTwo);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement