Javascript array methods & operations

87 0 0 0

Last Updated : 2020-10-24 11:02:39

Here are some of the most important and userd array functions and methods in Javascript.

Here are a list of the most important array methods in javascript.
Here is a samle of an array in Javascript


const names = ['Mohammed', 'Ahmed', 'Hassan', 'Nehad', 25, 'Ahmed'];


  • Find the index for a value within an array.

    1. Using IndexOf() & lastIndexOf (Please note these two methods don't work for references, such as array of objects, this won't work with objects)
      //ProtoType for this function , This will return the index if value is found or -1 other wise.
      // You can check if element is found or not using if(index !== -1)
      const index = Array.indexOf('value', startingPosition);

      //To find the first index for Ahmed in this array
      const index = data.indexOf('Ahmed')

      //To find the last index for Ahmed
      const index = data.lastIndexOf('Ahmed');​


    2. Using Find() and findIndex: these two functions will need an anonymous function as their parameter, the first will return the elemtn itself, the second will return the index.
      //---------------------------------->Array
      const data = [
      {name: "Ahmed"},
      {name: "Ali"},
      {name: "Hassan"}
      ]

      //---------------------------------->ProtoType
      data.find((element, index, fullArray)=>{
      return element.innerIndex == 'value'
      });

      //---------------------------------->Example, Search for Ahmed
      const AhmedObj = data.find((element, index, fullArray)=>{
      return element.name == 'Ahmed';
      });
      console.log(AhmedObj);

      //---------------------------------->Example, Search for Ahmed index
      const AhmedIndex = data.findIndex((element, index, fullArray)=>{
      return element.name == 'Ahmed';
      });
      console.log(AhmedIndex);

      //----------------------------------> Important note
      //These find function will return the object itself, So if you changed the name in the returned object, it will be changed in the original object itself.




  • Check if an array contains primitive value

    1. Using indexOf()
      const  theIndex = data.indexOf('Ahmed');
      if(theIndex !== -1) {
      console.log("Found");
      } else {
      console.log("Not found");
      }​


    2. Using includes()
      const  theIndex = data.includes('Ahmed');
      if(theIndex !== false) {
      console.log("Found");
      } else {
      console.log("Not found");
      }​




  • Looping through arrays

    1. Using For
      //------------------------------->First approach
      const newData = [];
      for(const name of data) {
      newData.push(name);
      }
      console.log(newData)'​

      //------------------------------->Second approach
      const newData = [];
      for(let i=0; i<data.length; i++) {
      newData.push(data[i]);
      }
      console.log(newData);


    2. Using forEach
      //----------------------------------> ProtoType
      data.forEach((value, index, fullArray)=>{
      });

      //----------------------------------> Example, create a new array of first array elements as objects
      const newData = [];
      data.forEach((value, index, fullArray)=>{
      const nameObj = {id: index, name:value};
      newData.push(nameObj);
      });
      console.log(newData)​




  • Transforming Arrays into another Array

    1. Using for & forEach()
      //------------------------------------------> for
      const prices = [10, 15, 20, 10.99];
      const tax = 0.19;
      const taxAdjustedPrices= [];

      for(const price of prices) {
      taxAdjustedPrices.push(price * (1 + tax));
      }

      console.log(taxAdjustedPrices);​
      //------------------------------------------> forEach
      const prices = [10, 15, 20, 10.99];
      const tax = 0.19;
      const taxAdjustedPrices= [];

      prices.forEach((price, indx, allPrices)=>{
      taxAdjustedPrices.push({id: indx, price: price*(1+tax)});
      });

      console.log(taxAdjustedPrices);


    2. Using map()
      //---------------------------------> The difference between this and forEach is that map() function will return the element in every iteration, and this will be added to the new created array without the original array being touched.
      const prices = [10, 15, 20, 10.99];
      const tax = 0.19;

      const taxAdjustedPrices = prices.map((price, indx, allPrices)=>{
      const priceObj = {id: indx, price: price*(1+tax)};
      return priceObj;
      });

      console.log(taxAdjustedPrices);​




  • Sorting Arrays 

    1. Using sort()
      //------------------------------> Sort sorts based on the starting string, so it will not sort the numbers in a correct way
      const prices = [10, 1.5, 20, 10.99];
      const sortedPrices = prices.sort();
      console.log(sortedPrices);

      //output : (6) [1.5, 10, 10.99, 11, 13, 2], which is definitely not the sorting we need.

      //------------------------------> Good way to sort numbers is as follows : because it compares two entries together
      const prices = [10, 1.5, 11, 2, 13, 10.99];
      const sortedPrices = prices.sort( (a,b)=> {
      if(a > b) {
      return 1;
      } else if(a == b) {
      return 0;
      } else {
      return -1;
      }
      });
      console.log(sortedPrices);
      //output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.

      //------------------------------> Same as above example
      prices .sort(function(a, b){return a - b});

      //------------------------------> Sorting Descending #1
      const prices = [10, 1.5, 11, 2, 13, 10.99];
      const sortedPrices = prices.sort( (a,b)=> {
      if(a > b) {
      return 1;
      } else if(a == b) {
      return 0;
      } else {
      return -1;
      }
      });
      console.log(sortedPrices.reverse());
      //output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.

      //------------------------------> Sorting Descending #2
      const prices = [10, 1.5, 11, 2, 13, 10.99];
      const sortedPrices = prices.sort( (a,b)=> {
      if(a > b) {
      return -1;
      } else if(a == b) {
      return 0;
      } else {
      return 1;
      }
      });
      console.log(sortedPrices);
      //output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.

      //-----------------------------> Sorting array of strings alphabitically whether starting with lower or uppercase:
      ["Foo", "bar"].sort(function (a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
      });

      //-----------------------------> Solution#2
      matchesFound.sort((a,b)=>{
      if(a < b) return -1;
      if(b < a) return 1;
      return 0;
      });




  • Reversing Arrays:

    1. Using reverse()
      const prices = ['Ahmed', 'Nehad', 'Basem', 'Kamel'];
      console.log(prices); //ouput: 'Ahmed', 'Nehad', 'Basem', 'Kamel'
      console.log(prices.reverse()); //ouput: 'Kamel', 'Basem', 'Nehad', 'Ahmed'​




  • Filtering Arrays:

    1. Using filter()
      const prices = [10, 1.5, 11, 2, 13, 10.99];
      const filteredArray = prices.filter( (price, indx, fullArray)=>{
      return price >= 10; //This will only return the elements that passes this condition
      });
      console.log(filteredArray);​

      //---------------------------------> A shorter way for the previous code will be :
      const filteredArray = prices.filter( price => price >= 10);




  • Reducing arrays:

    1. meaning to reduce an array to its sum , or its smallest value .. etc reduce a whole array to a one value or number.

    2. Sum array:

      1. Using for, forEach loop
        //--------------------> Using forEach
        const prices = [10, 1.5, 11, 2, 13, 10.99];
        let sum = 0;
        prices.forEach((price)=>{
        sum += price;
        });
        console.log(sum);

        //--------------------> Using for
        const prices = [10, 1.5, 11, 2, 13, 10.99];
        let sum = 0;
        for( let i=0; i<prices.length; i++) {
        sum += prices[i];
        }
        console.log(sum);​


      2. Using reduce:
        //--------------------------------> Prototype 
        /*
        - previousVal : the previous/last value, first time it will be equal to the second parameter passed to reduce function which is 0 in our case
        - currentVal: will be the current value of the element in the array.
        - currIndex: the current element index.
        - fullArray : is the full array being reduced.
        */
        const sum = prices.reduce((previousVal, currentVal, CurrentIndx, fullArray)=>{
        return previousVal + currentVal;
        }, 0);
        console.log(sum);

        //------------------------------> Here is the example solution
        const prices = [10, 1.5, 11, 2, 13, 10.99];
        const sum = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
        return previousVal + currentVal;
        }, 0);
        console.log(sum);​

        //-----------------------------> A short version of the previous code
        const prices = [10, 1.5, 11, 2, 13, 10.99];
        const sum = prices.reduce((previousVal, currentVal)=> previousVal + currentVal, 0);
        console.log(sum);




    3. Least/Smallest/min value in array
      const prices = [10, 1.5, 11, 2, 13, 1.25, 10.99];

      const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
      if(previousVal == 0) {
      return currentVal;
      } else if(currentVal < previousVal){
      return currentVal;
      } else {
      return previousVal;
      }
      }, 0);
      console.log(leastValue);​
      //------------------------------------> Another short version

      const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
      return (currentVal < previousVal)?currentVal:previousVal;
      });

      //----------------------------------> A third short version
      const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
      if(currentVal < previousVal){
      return currentVal;
      } else {
      return previousVal;
      }
      });

      //--------------------------------------> Another very efficient way .. using the spread operator, which will get all the elements of the array
      console.lo(Math.min(...prices));


    4. Greatest/Biggest/max value in an array
      const prices = [10, 1.5, 11, 2, 13, 1.25, 10.99];

      const greatestValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
      return (currentVal < previousVal)?previousVal:currentVal;
      });

      console.log(greatestValue);​
      //--------------------------------------> Another very efficient way .. using the spread operator, which will get all the elements of the array
      console.lo(Math.max(...prices));




  • map().reduce()

    • We can chain array methods as follows:
      const originalArray = [{price: 350},{price: 100},{price: 50},{price: 410}];
      const transformedArray = originalArray.map(item=>item.price); //output [350,100,50,410]
      const sum = transformedArray.reduce((sumVal, currVal)=>sumVal + currVal, 0); //output: 910

      console.log(transformedArray, sum);
      //----------------> Another solution without map
      const sum2 = originalArray.reduce((sumVal, currVal)=>sumVal + currVal.price, 0);
      console.log(sum2); //output: 910
      //----------------> Athird shorter chaining map and reduce
      sum3 = originalArray.map(item=>item.price).reduce((sumVal, currVal)=>sumVal + currVal,0);
      console.log(sum3); //output: 910​




  • Split string into an array, using split()
    //---------------------->ProtoType
    //string.split('separator', numberOfElements);

    //---------------------->Example
    const stringData = "Mohammed;10.99;2001";
    const transformedData = stringData.split(";");
    console.log(transformedData); //output: ['Mohammed', 10.99, 2001];


  • join array elements into a string, using join()
    const nameFragments = ['Mohammed', 10.99, 2001];
    const nameString = nameFragments.join(",");
    console.log(nameString); //output: Mohammed,10.99,2001


  • check if an array, bacause using typeof will always return an object
    //----------------------------> Solution #1
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    typeof fruits; // returns object, this might be a problem

    //----------------------------> Solution #2
    Array.isArray(fruits); // Will return true if fruits is an array, bu this is not supported in old browsers

    //----------------------------> Solution #3
    function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
    }
    //----------------------------> Solution #4
    fruits instanceof Array; // returns true


  • -

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .