Last active
          September 2, 2022 18:59 
        
      - 
      
- 
        Save ali-aka-ahmed/fdbd1a0a493f198a7d6d36e3120de43c to your computer and use it in GitHub Desktop. 
    Common operations on arrays
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /* | |
| * ================================= | |
| * =========== SEARCH ============== | |
| * ================================= | |
| */ | |
| let array = [1, 2, 3, 4, 5] | |
| let val = array.find((val) => { | |
| if (val === 1) { | |
| return true | |
| } | |
| }) | |
| // val = 1 | |
| // array = [1, 2, 3, 4, 5] | |
| // same thing, but written more succintly | |
| // let val = array.find((val) => return val === 1) | |
| /* | |
| * ================================= | |
| * =========== FILTER ============== | |
| * ================================= | |
| */ | |
| let array = [1, 2, 3, 4, 5] | |
| let val = array.filter((val) => { // 1 | |
| if (val % 2 === 0) { // is it even? | |
| return true | |
| } | |
| }) | |
| // val = [2, 4] | |
| // array = [1, 2, 3, 4, 5] | |
| // same thing, but written more succintly | |
| // let val = array.filter((val) => return val % 2 === 0) | |
| /* | |
| * ================================= | |
| * =========== MODIFY ============== | |
| * ================================= | |
| */ | |
| let array = [1, 2, 3, 4, 5] | |
| let newList = array.map((val) => { | |
| return val + 1 | |
| }) | |
| // newList = [2, 3, 4, 5, 6] | |
| // array = [1, 2, 3, 4, 5] | |
| // same thing, but written more succintly | |
| // let newList = array.map((val) => val + 1) | |
| /* | |
| * ================================= | |
| * =========== OTHER ============== | |
| * ================================= | |
| */ | |
| // This is a forEach function. It isn't as much an array 'search', 'modify', or 'filter' option. | |
| // It's more of a shorthand for a for loop. This allows you to go through | |
| // each item in an array without having to write list[i] and declare and increment i | |
| let emptyList = [] | |
| array.forEach((val) => { | |
| emptyList.push(val) | |
| }) | |
| // emptyList = [6, 7, 8, 9, 10] | |
| // array = [1, 2, 3, 4, 5] | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment