All  About  Arrays  In  Javascripts []

All About Arrays In Javascripts []

·

5 min read

what is an Arrays?

  • they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value.

Creating arrays :-

Arrays consist of square brackets and items that are separated by commas.

  1. Suppose we want to store a shopping list in an array. Paste the following code into the console:
          const shopping = ['iphone', 'watch', 'earbuds', 'laptops', 'speakers'];
          console.log(shopping);
    

2. In the above example, each item is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays.

       const sequence = [1, 1, 2, 3, 5, 8, 13];
       const random = ['tree', 795, [0, 1, 2]];

Finding the length of an array:-

  • You can find out the length of an array in exactly the same way as you find out the length (in characters) of a string — by using the length property. Try the following:

           const shopping = ['iphone', 'watch', 'earbuds', 'laptops', 'speakers'];
           console.log(shopping.length);  // 5
    

Accessing and modifying array items:-

  • Items in an array are numbered, starting from zero. This number is called the item's index. So the first item has index 0, the second has index 1, and so on. in the same way that you accessed the letters in a string.

1. accessed the letters in a string. const shopping = ['iphone', 'watch', 'earbuds', 'laptops', 'speakers']; console.log(shopping[0]); // returns "iphone"

2. You can also modify an item in an array by giving a single array item a new value. Try this:

        const shopping = ['iphone', 'watch', 'earbuds', 'laptops', 'speakers'];
        shopping[0] = 'notepad';
        console.log(shopping);
        // shopping will now return ['notepad', 'watch', 'earbuds', 'laptops', 'speakers']

3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together.

             const random = ['tree', 795, [0, 1, 2]];
              random[2][2];

Finding items in an array:-

  • You can find the index of a particular item using the indexOf() method. This takes an item as an argument and returns the index, or -1 if the item was not found in the array:

       const birds = ['Parrot', 'Falcon', 'Owl'];
       console.log(birds.indexOf('Owl'));   //  2
       console.log(birds.indexOf('Rabbit')); // -1
    

Adding items

  • To add one or more items to the end of an array we can use push(). Note that you need to include one or more items that you want to add to the end of your array.

           const countries = ['india', 'sweden'];
           countries.push('india');
           console.log(countries);      // [ "iran", "sweden", "india" ]
           countries.push('USA', 'iraq');
           console.log(countries);      // [ "iran", "sewden", "india", "USA", "iraq" ]
    
  • The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:

           const countries = ['iran', 'sewden'];
           const newLength = countries.push('canada');
           console.log(countries);     // [ "iran", "sewden", "canada" ]
           console.log(newLength);  // 3
    
  • To add an item to the start of the array, use unshift() :

          const countries = ['iran', 'sewden'];
          countries.unshift('italy');
          console.log(countries);     // [ "italy", "iran", "sewden" ]
    

Removing items

  • To remove the last item from the array, use pop() .

        const countries = ['iran', 'sewden'];
       countries.pop();
        console.log(countries);     // [ "iran" ]
    
  • The pop() method returns the item that was removed. To save that item in a To remove the first item from an array, use shift():new variable, you could do this:

        const countries = ['Iran', 'sewden'];
        const removedCountry = country.pop();
        console.log(removedCountry);   // "sewden"
    
  • To remove the first item from an array, use shift() :

        const countries = ['Iran', 'Sewden'];
        Countries.shift();
        console.log(countries);     // [ "Sewden" ]
    
  • If you know the index of an item, you can remove it from the array using splice():

       const countries = ['Iran', 'Sewden', 'Germany', 'Australia'];
       const index = Countries.indexOf('Sewden');
       if (index !== -1) {
       Countries.splice(index, 1);
       }
       console.log(Countries);     // [ "Iran", "Germany", "Australia" ]
    
  • In this call to splice() ,the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:

    const Countries = ['Iran', 'Sewden', 'Germany', 'Australia'];
    const index = Countries.indexOf('Sewden');
    if (index !== -1) {
    Countries.splice(index, 2);
    }
    console.log(Countries);     // [ "Iran", "Australia" ]
    

Accessing every item

  • Very often you will want to access every item in the array. You can do this using the for...ofstatement:

       const birds = ['Parrot', 'Falcon', 'Owl'];
    
       for (const bird of birds) {
       console.log(bird);
       }
    
  • Sometimes you will want to do the same thing to each item in an array, leaving you with an array containing the changed items. You can do this using map().The code below takes an array of numbers and doubles each number:

      function double(number) {
      return number * 2;
      }
      const numbers = [5, 2, 7, 6];
      const doubled = numbers.map(double);
      console.log(doubled);  // [ 10, 4, 14, 12 ]
    

Filter in array

  • To get a filter in array data, you used filter() method

    const state = ["karnataka","GOA","Delhi","Mumbai"];
    const result = state.filter(s=>s.length>5);
    console.log(result);//[ 'GOA', 'Mumbai' ]
    

order in array

  • To order in array data, you used sort() method

    const state = ["karnataka","GOA","Delhi","Mumbai"];
    const result = state.sort();
    console.log(result);//[ 'karnataka', 'Delhi', 'Mumbai', 'GOA' ]
    

every() method use in array

  • The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

     const state = ["karnataka","GOA","Delhi","Mumbai"];
     var result = state.every((e) => {
         return typeof e === 'string';
      });
     console.log(result);//true
    

How to Check if the Given Value is an Array:

  • To check whether the given value is an array or not we use Array.isArray(value)method. This method returns true if the given value is an array.

     Array.isArray('simran');   // false
    Array.isArray(['simran', 146, 52]);  // true
    Array.isArray(undefined);  // false
    Array.isArray({totalMarks: 93}); // false
    

javascript.com/learn/arrays

logo.png

Happy Learning!!

Did you find this article valuable?

Support Syed Riza by becoming a sponsor. Any amount is appreciated!