Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /*
  2. Happy Tuesday daily_programmer!
  3.  
  4. 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]
  5.  
  6. Please DM me with ideas for future problems. When you have completed it post a link to your solution.
  7.  
  8. *if you have a question about someones solution please use a thread under their posted link*
  9. */
  10.  
  11. // alternate and combine arrays
  12. function altCombineArrays(firstArray, secondArray) {
  13. // set up our result variable
  14. var result = [];
  15. // set up our length variable
  16. var length = 0;
  17. // see which array is longer and set that as our length
  18. if (firstArray.length > secondArray.length) {
  19. length = firstArray.length;
  20. } else {
  21. length = secondArray.length;
  22. }
  23. // run our for loop the length of our longest array
  24. for (var i = 0; i < length; i++) {
  25. // only push from first array if we still have a value
  26. if (i < firstArray.length) {
  27. result.push(firstArray[i]);
  28. }
  29. // only push from second array if we still have a value
  30. if (i < secondArray.length) {
  31. result.push(secondArray[i]);
  32. }
  33. }
  34. // return our result
  35. return result;
  36. }
  37.  
  38. var arrayOne = ['a', 'b', 'c', 'd', 'e'];
  39. var arrayTwo = [1, 2, 3, 4, 5, 6, 7, 8];
  40.  
  41. altCombineArrays(arrayOne, arrayTwo);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement