Advertisement
binibiningtinamoran

CustomConcat.js

May 27th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WRITE A CUSTOM CAONCAT METHOD
  2.  
  3.  
  4.  
  5. // Write a naive version of the concat() method.
  6.  
  7. let customConcat = (firstArray, secondArray) => {
  8.     let tempArray = [];
  9.  
  10.     // "Merge" the 2 arrays!
  11.     for (let i = 0, length = firstArray.length; i < length; i++) {
  12.         tempArray[i] = firstArray[i];
  13.     }
  14.     for (let i = 0, length = secondArray.length; i < length; i++) {
  15.         tempArray[i+firstArray.length] = secondArray[i];
  16.     }
  17.     // End merging
  18.  
  19.     let newArray = [];
  20.     let uniques = tempArray.length;
  21.  
  22.     for(let i = 0; i < uniques; i++) {
  23.         for (let j = i+1; j < uniques; j++) {
  24.             if(tempArray[i] === tempArray[j]) { // if adjacent elements are equal/same
  25.                 tempArray[j] = tempArray[uniques-1]; // replace duplicate element with last unique element
  26.                 uniques--;
  27.                 j--;
  28.             }
  29.         }
  30.     }
  31.  
  32.     // Copy array (without duplicates!) to newArray
  33.     // At this point, duplicate elements in tempArray[] have been removed!
  34.     for (let i = 0; i < uniques; i++) {
  35.         newArray[i] = tempArray[i];
  36.     }
  37.  
  38.     return newArray;
  39. };
  40.  
  41. console.log(customConcat(['a','b','c','d'],[1,2,3]));
  42. console.log(customConcat([1,2,3,99,99,99,99],[2,4]));
  43. console.log(customConcat(['a','b'],['b','c']));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement