Advertisement
binibiningtinamoran

Array.find

May 27th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WRITE A CUSTOM ARRAY.FIND METHOD
  2.  
  3. // Function that accepts an array and a number as parameters.
  4. // The function shall return the element larger than the number parameter.
  5. // If no element greater than the search value is found, function shall return the value of the search value.
  6. let customArrayFindVersionOne = (array, compareValue) => {
  7.  
  8.     let greaterValue = compareValue; // if no value found greater than compareValue, return -1
  9.     let found = false;
  10.  
  11.     for (let i = 1, length = array.length; i <= length && !found; i++) {
  12.         if (array[i] > compareValue) {
  13.             greaterValue = array[i];
  14.             found = true;
  15.         }
  16.     }
  17.     return greaterValue;
  18. };
  19.  
  20. // FIRST FUNCTION, VERSION 2
  21. let customArrayFindVersionTwo = (array, compareValue) => {
  22.  
  23.     let greaterValue = compareValue; // if no value found greater than compareValue, return compareValue
  24.     let found = false;
  25.  
  26.     for (let element of array) {
  27.         if (element > compareValue && !found) {
  28.             greaterValue = element;
  29.             found = true;
  30.         }
  31.     }
  32.     return greaterValue;
  33. };
  34.  
  35. let customArrayFindVersionThree = (array, compareValue) => {
  36.     let greaterValue = compareValue;
  37.     let index = 0;
  38.     let length = array.length;
  39.     let found = false;
  40.  
  41.     while (index < length && !found) {
  42.         if (array[index] > compareValue) {
  43.             greaterValue = array[index];
  44.             found = true;
  45.         }
  46.         index++;
  47.     }
  48.     return greaterValue;
  49. };
  50.  
  51. // Tests for FIRST FUNCTION
  52. console.log(customArrayFindVersionOne([5,15,40],41)); // returns -1 since value is not found!
  53. console.log(customArrayFindVersionTwo([5,40,15], 15)); // returns 40, since 40 > 15
  54. console.log(customArrayFindVersionTwo([1,2,3,4,66,77,14,5],1));
  55. console.log(customArrayFindVersionThree([5,15,40], 5));
  56. console.log(customArrayFindVersionTwo([10,12,14,18,56,90,900,1000],0));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement