Skip to content

Instantly share code, notes, and snippets.

@Mohamed-Code-309
Last active March 11, 2023 11:26
Show Gist options
  • Save Mohamed-Code-309/b2e7867077024aca7b3c75d50e3d94da to your computer and use it in GitHub Desktop.
Save Mohamed-Code-309/b2e7867077024aca7b3c75d50e3d94da to your computer and use it in GitHub Desktop.
JavaScript : New Array Methods

Create New Array Methods in JavaScript

We are going to add new methods to the Array() object using Array.prototype property.

Prototype is a property that is associated with every function and object by default in JavaScript.

With Array.prototype we can access existing methods in the Array() object like push(), pop(), map() etc. or add new methods that will be available to every array we define.

limit βœ‹

extract a specific number of elements from an array starting from first element.

Array.prototype.limit = function(num){
    var result = [];
    //var length = this.length;         
    //if(num > length) num = length //optinoal: to prevent return undefined
    for(i =0; i< num; i++){
       result.push(this[i])   //this: refers to the array  
   }
   return result;
}

//example: takes only 4 first elements in the array
var arr = [100, 2, 33, 10, 77, 5, 97, 200]
console.log(arr.limit(4)); //[100, 2, 33, 10]

intersect πŸ’•

return only the elements that are shared between two arrays.

Array.prototype.intersect = function(array){
     var results = [];
     this.forEach(function(item1){ 
         array.forEach(function(item2){
             if(item1 == item2 && typeof item1 == typeof item2){
                  results.push(item1) //or item2
              } 
         })
     })
     return results;
}

//example:
//intersect takes an array as a parameter
var arr1 = [1,2,3,4]
var arr2 = [3,4,5,6]
var intersection = arr1.intersect(arr2);
console.log(intersection) //[3, 4]

except ❓

return elements from one array which not exist in another array.

Array.prototype.except = function(array){
    var results = [];
    this.forEach(function(elem){
        if(!array.includes(elem)){
            results.push(elem)
        }
    })
    return results;
}

//example:
//except takes an array as a paramter
var arr1 = [10, 20, 30]
var arr2 = [30, 40, 50]
console.log(arr1.except(arr2)); //[10, 20]
console.log(arr2.except(arr1)); //[40, 50]

//arr1.intersect(arr2) == arr2.intersect(arr1)
//arr1.except(arr2)    !=   arr2.except(arr1)

flatten ✌️ ➑️ ☝️

takes 2-dimensional array and decrees it by one level.

Array.prototype.flatten = function(){
     var results = [];
     this.forEach(function(subArray){
         subArray.forEach(function(item){
              results.push(item)
         })
     })
     return results;
}

//example: make sure each element is another array or the function will result in an error
var arr = [[1, 2, 3], [4, 5, 6], [7, 8]] 
console.log(arr.flatten()); //[1, 2, 3, 4, 5, 6, 7, 8]

distinct πŸ‘Œ

return only distinct (different) elements from an array.

Array.prototype.distinct = function(){
     var uniques = [];
     var temp = [];
     temp = this.map(item => item).sort(); //sort is important
     var counter = 0;
     for(i=0; i< temp.length; i++){
        var elem = this.filter(elem => elem == temp[i]).length - counter;      
        if(!(elem > 1)){
            uniques.push(temp[i]);
            counter = 0;
        }
        else{
            counter++;
        }
    }
    return uniques;
}

//example
var arr = [1, 2, 3, 4, 3, 4, 5, 5, 6, 7, 6]
console.log(arr.distinct()) //[1, 2, 3, 4, 5, 6, 7]

Notes πŸ“

  • All the created methods do not change the original array, they are returning a new one.
  • You can change the name of the methods to whatever you like. (limit can be stop, distinct can be unique, etc.)

Related Content:

βœ”οΈ Mutated vs Non-Mutated Array Methods
βœ”οΈ Top 13 Javascript Interview Questions You Should Answer !

Links:

πŸ•΄οΈ Linkedin: Dragon Slayer 🐲
πŸ“ Articles: All Articles written by D.S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment