JavaScript Array

 JavaScript Array

 An array is a special variable, which can hold more than one value:

1.  Creating an Array

 
    const arr = [232,"Array", false, true];
    console.log(arr);


 
    output: 
    [ 232, 'Array', false, true ]
  
 

 

2.  Spaces and line breaks are not important. A declaration can span multiple lines


    const cars = ["Audi","Mercedes",
    "Lamborghini","Jugar","BMW",
    "This is an Array",8787,9789
    ];
    console.log(cars);
 
    output: 
  
    [
      'Audi',
      'Mercedes',
      'Lamborghini',
      'Jugar',
      'BMW',
      'This is an Array',
      8787,
      9789
    ]

 

 3. You can also create an array, and then provide the elements:


    const arr =[];
    arr[0] = "Arrays";
    arr[1] = "Strings";
    arr[2] = 'This is an array element';
    console.log(arr);

    output: 
    [ 'Arrays', 'Strings', 'This is an array element' ]

 

 

 
    const arr =[];
    arr[0] = "Arrays";
    arr[1] = "Strings";
    arr[2] = 'This is an array element';

    arr[0] = "Javaascript";
    console.log(arr);
    console.log(arr[0]);
    console.log(arr[1]);
     
    output:
    
    [ 'Javaascript', 'Strings', 'This is an array element' ]
    Javaascript
    Strings

 

4. The following example also creates an Array, and assigns values to it.

 
    const cars = new Array("Saab","Tesla", "BMW");
    console.log(cars);
     
    output:
    [ 'Saab', 'Tesla', 'BMW' ]     
 

 

 5. Accessing Array Elements

 
    const arrr = ["element","Method","Binary","Trees", "prototype","work hard"];
    console.log(arrr);
    console.log(arrr[3])
    console.log(arrr[0][1]);
    console.log(arrr[4]);
 
    output:  
    
    [ 'element', 'Method', 'Binary', 'Trees', 'prototype', 'work hard' ]
    Trees
    l
    prototype 
 

 

 6. Changing an Array Element


    let arrEle = ["Paris","Hong kong","Moscow","Tokyo","New york"];
    console.log(arrEle);
 
    arrEle[0] = "Japan";        // changing an array element 0 index.
 
    console.log(arrEle);
 
    output: 
    [ 'Paris', 'Hong kong', 'Moscow', 'Tokyo', 'New york' ]
    [ 'Japan', 'Hong kong', 'Moscow', 'Tokyo', 'New york' ]

 

 

N.B Arrays are Objects

 

7.  Array sort()

 
    let arrEle = ["Paris","Hong kong","Moscow","Tokyo","New york"];
    console.log(arrEle.sort());
     
    output:
    [ 'Hong kong', 'Moscow', 'New york', 'Paris', 'Tokyo' ] 
 

 


    let arrEle = [454,5445,"Paris","Hong kong","Moscow","Tokyo","New york",true,false];
    console.log(arrEle.sort());
 
   output:  
    [
      454,         5445,
      'Hong kong', 'Moscow',
      'New york',  'Paris',
      'Tokyo',     false,
      true
    ]

 

 

 Accessing the First Array Element


    const varr = [
        "Hello there", "Planet",
        "Galaxy", "Universe",
        010101, true,"Die Hard"
    ];

    console.log(varr[0]);
 
    output: 
    Hello there

 

 Accessing the Last Array Element


    const arr = [
        "Hello there", "Planet",
        "Galaxy", "Universe",
        010101, true,"Die Hard"
    ];

    console.log(arr[arr.length -1]);
 
 
    output:  
    Die Hard

 

8.  Adding Array Elements.

The easiest way to add a new element to an array is using the push() method.

 
    const city = ["Mumbai","Chennai","Delhi","Pune"];
    console.log(city);
    city.push("Bengalore");
    console.log(city);
 
 
    output:
     
    [ 'Mumbai', 'Chennai', 'Delhi', 'Pune' ]
    [ 'Mumbai', 'Chennai', 'Delhi', 'Pune', 'Bengalore' ]

  

New element can also be added to an array using the length property.


    const city = ["Mumbai","Chennai","Delhi","Pune"];
    console.log(city);
    city[city.length] = "Heyderabad";
    console.log(city);
 
    output:
    [ 'Mumbai', 'Chennai', 'Delhi', 'Pune' ]
    [ 'Mumbai', 'Chennai', 'Delhi', 'Pune', 'Heyderabad' ]

 

Note:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.   




9. javaScript code for     concat() method

 
    function func1(){
        let num1 = [11,12,13];
        let num2 = [14,15,16];
        let num3 = [17, 18, 19];
        console.log(num1.concat(num2,num3)) ;
    }
    func1();
 
    output:  
    [
      11, 12, 13, 14, 15,
      16, 17, 18, 19
    ]
 


    const num1 = [11,12,13];
    num2 = [14,15,16];
    num3 = [17,18,19];
    console.log(num1.concat(num2,num3));
     
    output:
    [
      11, 12, 13, 14, 15,
      16, 17, 18, 19
    ]
  
     

 

    var alpha = ['a','b','c'];
    console.log(alpha.concat(1,[2,3]));
 
    output:
    [ 'a', 'b', 'c', 1, 2, 3 ]
 

 

    let num1 = [[23]];
    let num2 = [89, [67]];
    console.log(num1.concat(num2));
     
    output:
    [ [ 23 ], 89, [ 67 ] ]
 

 


    function fun(){
        let alpha = ["a","b","c"];
        console.log(alpha.concat(1,[2,3]));
    }
    fun();
    
     output:
    [ 'a', 'b', 'c', 1, 2, 3 ]

 


    let alpha = ["a", "b","c"];
    console.log(alpha.concat(1,[2,3]));

    output:    
    [ 'a', 'b', 'c', 1, 2, 3 ]
 

 

 

 

10.  JavaScript Array     copyWithin() Method

    const array = [1,2,3,4,5,6,7];
    console.log(array.copyWithin(0,3,6));   // copyWithin(Target,start,end)
     
     output:  
    [
      4, 5, 6, 4,
      5, 6, 7
    ]
 

 

 

 
    const arr = [1,2,3,4,5,6,7];
    console.log(arr.copyWithin(0,4));   // output: 5,6,7,4,5,6,7
 
    output:      
    [
      5, 6, 7, 4,
      5, 6, 7
    ]

 

 

 

 11. Array     fill()     Method

 

 
    function fun(){
        let arr = [1,23,46,58];
        // fill array with 87
        arr.fill(99);
        console.log(arr);
    }
    fun();
 
    output:  
    [ 99, 99, 99, 99 ]


 

 
    function fun(){
        let arr = [1,23,46,58];
        // fill array with 87
        arr.fill("Die Hard");
        console.log(arr);
    }
    fun();
 
    output:  
    [ 'Die Hard', 'Die Hard', 'Die Hard', 'Die Hard' ]

 

 

arr.fill(value, start, end)

Parameters: This method accepts three parameters as mentioned above and described below: 

 

 
    let arr = [1,23,46,58];
    arr.fill(100, 1,3);     // fill(value, start, end)
    console.log(arr);
 
    output:  
    [ 1, 100, 100, 58 ] 

 

 
    let arr = ["move","system","run",true];
    arr.fill("Now",2);
    console.log(arr);
 
    output:    
    [ 'move', 'system', 'Now', 'Now' ]

 

 
    function myarr(){
        let arr = [1,3,4,58];
        arr.fill(87,1,3);        // fill(value,start,end)
        console.log(arr);
    }
    myarr();
 
 
    output:  
    [ 1, 87, 87, 58 ]

 

 

 

 12. JavaScript Array filter() Method

 

 
    function canVolte(age){
        return age >= 18;
    }

    function fun1(){
        let filtered = [24,33,16,40].filter(canVolte)
        console.log(filtered);
    }
    fun1();
 
     output: 
    [ 24, 33, 40 ]

 

 
    function isPositive(value){
        return value > 0;
    }

    let filtered = [11,1,0,-1,899,-1,-5,232].filter(isPositive);
    console.log(filtered);
 
    output: 
    [ 11, 1, 899, 232 ] 
 

 

 
    function isEven(value){
        return value % 2 ===0;
    }
    let fil = [11,22,23,45,33,123,68,58,54,89].filter(isEven);
    console.log(fil);
     
    output: 
    [ 22, 68, 58, 54 ]

 

 


    function isEv(value){
        return value % 2 ===0;
    }
    function resl(){
        let arr = [23,56,41,25,38,25,80].filter(isEv);
        console.log(arr);
    }
    resl();
 
    output: 
    [ 56, 38, 80 ]
 

 

 

 

 

 

 13.  JavaScript Array find() Method


    var arr = [-10,-0.20,0.30,-40,-50,5];

    var found = arr.find(function (element){
        return element > 0;
    });
    console.log(found);
 
 
    output:  0.3

 

 
    let arr = [20,30,40,50,60];

    let findd = arr.find(function (lan){
        return lan > 40;
    })
    console.log(findd);
 
    output:  50

 


    const arr = [2,4,7,8,9];

    const total = arr.find(function (arr){
        return arr > 4;
    })
    console.log(total);
 
    output:  7

 

 

 14.  JavaScript Array  findIndex()  Method

findIndex() method to find the index of positive number from an array.

 
positive element at index 3. So it print 3.



    let arr = [-10, -0.30,-40,0.20,-736]

    let fin = arr.findIndex(function (arr){
        return arr > 0;
    })
    console.log(fin);
 
    output:  3  



 
    function isOdd(element, index, array){
        return (element % 2 ==1);
    }
    console.log([4,7,8,12].findIndex(isOdd));
 
    output:  1   


  
 
 
 
 
The arr.findIndex() method used to return the index of the first element in a given array that satisfies the provided testing function. Otherwise, -1 is returned.
 


    function isOdd(element, index, array){
        return (element % 2 ==1);
    }
    console.log([4,6,8,12].findIndex(isOdd));

    output:  -1   

 

 
    let array = [10,20,30,110,70];

    function index_element(element){
        return element > 25;
    }
    console.log(array.findIndex(index_element));
 
    output:  2

 

 
    function isPrime(n){
        if(n === 1){
            return false;
        }
        else if(n === 2){
            return true;
        }
        else{
            for(let x = 2; x < n; x++){
                if(n % x === 0){
                    return false;
                }
            }
            return true;
        }
    }

    console.log([4,6,8,12].findIndex(isPrime));
    console.log([4,6,7,12,18].findIndex(isPrime));
 
    output:  
    -1
    2

 

 

 15.  JavaScript Array     flat()     Method

The arr.flat() method was introduced in ES2019. It is used to flatten an array, to reduce the nesting of an array.

The flat() method is heavily used in functional programming paradigm of JavaScript. Before flat() method was introduced in JavaScript, various libraries such as underscore.js were primarily used.



    const numbers = [["1","2"], ["3","4",["5",["6"],"7"]]];
    const flatNumbers = numbers.flat(Infinity);
    console.log(flatNumbers);
 
    output: 
    
    [
      '1', '2', '3',
      '4', '5', '6',
      '7'
    ]

 

 

 


    let nestedArray = [1,[2,3],[[]],[4, [5]],6];


    let zeroFlat = nestedArray.flat(0);
    console.log(`Zero level flattened array: ${zeroFlat}`);

    let oneFlat = nestedArray.flat(1);
    console.log(`One level flattened array: ${oneFlat}`);


    let twoFlat = nestedArray.flat(2);
    console.log(`Two level flattened array: ${twoFlat}`);

    let threeFlat = nestedArray.flat(3);
    console.log(`Three levels flattened array: ${threeFlat}`);
 
    output: 

    Zero level flattened array: 1,2,3,,4,5,6
    One level flattened array: 1,2,3,,4,5,6
    Two level flattened array: 1,2,3,4,5,6
    Three levels flattened array: 1,2,3,4,5,6

 

 

 
    let arr = [1,2,3,,4]
    let newArr = arr.flat();
    console.log(newArr);
 
    output:
    [ 1, 2, 3, 4 ]

 

 

 

 16. JavaScript | array .flatMap()

 

 

17.  JavaScript Array forEach() Method

 


    function func(){
        const items = [12,24,36];
        const copy = [];
        items.forEach(function (item){
            copy.push(item + item +2);
        })
        console.log(copy);
    }
    func();
 

    output:
    [ 26, 50, 74 ]
 


 
    const items = [1,29,47];
    const copy = [];

    items.forEach(function(item){
        copy.push(item * item)
    });
    console.log(copy);
 
    output:
    [ 1, 841, 2209 ]

 

 

 18.  JavaScript | Array     from()     Method

 

 

 

 19. JavaScript Array includes() Method

 The array.includes() method is used to know either a particular element is present in the array or not and accordingly, it returns true or false i.e, if the element is present, then it returns true otherwise false.
 
 
    let name = ["gfg", "cse", "geeks","portal"];
    let a = name.includes('gfg');
    console.log(a);
 
    output: true

 

    let arr = [1,2,3,4,5];
    let aa = arr.includes(2);
    console.log(aa);
 
    output: true 
 

 

 
    let arr = [1,2,3,4,5].includes(2);
    console.log(arr);
 
    output: true 




    let arr = [1,2,3,4,5].includes(7);
    console.log(arr);
 
    output: false 
 

 

 

 

 

 20.  JavaScript Array indexOf() Method

The arr.indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. 
 
 
array.indexOf(element, start)
This method accepts two parameters as mentioned above.
 



    let arr = ['somebody', 'told', 'you', 'how', 'much', 'i care','you'];
    let fin = arr.indexOf("how");
    console.log(fin);

    output: 3




    const arr2 = [1,2,3,4,5,6].indexOf(4);
    console.log(arr2);
 
    output: 3

 

 In this example the method will searched for the element 9 in that array if not found then return -1.


    const num = [1,2,3,4,5,6,7].indexOf(9);
    console.log(num);
 
    output: -1

 

 

 

 

 21. JavaScript Array     isArray()     Method

The arr.isArray() method determines whether the value passed to this function is an array or not. This function returns true if the argument passed is array else it returns false.
 

    function func(){
        console.log(Array.isArray('football'));
    }
    func();

    output: false

 


    function func(){
        console.log(Array.isArray(['football']));
    };
    func();
 
    output: true

 


    function f2(){
        console.log(Array.isArray({name: "Lin"}))
    };
    f2();
 
    output: false

 

 

 

 22. JavaScript Array join()  Method

 The arr.join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).
 

    function func(){
        let a = [1,2,3,4,5,6];
        console.log(a.join(" | "));
    }
    func();
 
    output: 
    1 | 2 | 3 | 4 | 5 | 6
 

 


    function func(){
        let a = [1,2,3,4,5,6];
        console.log(a.join(" waw "));
    }
    func();
 
    output: 
    1 waw 2 waw 3 waw 4 waw 5 waw 6

 



    function fun(){
        let a = [1,2,3,4,5,6,7];
        console.log(a.join(''));
    }
    fun();
 
    output: 
    1234567

 

 

 

 

  23.  JavaScript Array keys() Method

 The array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array.

 


    let a = [5,6,7];

    let iterator = a.keys();

    for(let key of iterator){
        console.log(key + ' ');
    };
 
    output:
    0
    1
    2
 

 

 

 


    const arr = ["Learning","JavaScript","Array","GeeksForGeeks","OK"];

    let iterator = arr.keys();

    for(let key of iterator){
        console.log(key);
    }

    output:
    0
    1
    2
    3
    

 

 

 

 

 24.  JavaScript Array  lastIndexOf()  Method

 The arr.lastIndexOf() method is used to find the index of the last occurrence of the search element provided as the argument to the function.
 

 

    
 let language = ["python","Java","C++","C#","JS","GO","Ruby","swift"];
  let tat = language.lastIndexOf("C#");
  console.log(tat);
 
    output: 3

 


   let language = ["python","Java","C++","C#","JS","GO","Ruby","swift"];
   let tat = language.lastIndexOf("python");
   console.log(tat);
 
    output: 0

 

 
    let num = [1,2,3,4,5,6].lastIndexOf(3);
    console.log(num);
     output: 2
 

 

 


    let num = [1,2,3,4,5,6].lastIndexOf(8);
    console.log(num);
 
     output: -1

 

 


    let language = ["python","Java","C++","C#","JS","GO","Ruby","swift"];
    let tat = language.lastIndexOf("R");
    console.log(tat);
 
     output: -1

 

 

 

 

 25.  JavaScript Array  map()  Method

 The arr.map() method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order.

 


    function fun(){
        let arr = [14,10,11,00];
        let newArr = arr.map(Math.sqrt);
        console.log(newArr);
    }
    fun();

    output: 
    [ 3.7416573867739413, 3.1622776601683795, 3.3166247903554, 0 ]
 

 

 


    let arr = [2,56,78,34,65];
    let newArr = arr.map(function(num){
        return num / 2;
    })
    console.log(newArr);
    
    output: 
    [ 1, 28, 39, 17, 32.5 ]

 


    const arr = [10, 64,121,23];
    const newArr = arr.map(Math.sqrt);
    console.log(newArr);
 
    output:   
    [ 3.1622776601683795, 8, 11, 4.795831523312719 ]
 

 

 
    function fun(){
        let arr = [2,56,78,34,65];

        let newArrr = arr.map(function (num){
            return num/2;
        })
        console.log(newArrr);
    }
    fun();
 
    output:     
    [ 1, 28, 39, 17, 32.5 ]
 

 


    function funnn(){
        let arr = [10,64,121,23];

        let newArr = arr.map(Math.sqrt);
        console.log(newArr);
    }
    funnn();
 
   output: 
   [ 3.1622776601683795, 8, 11, 4.795831523312719 ]


 

 

 

 

 26.  JavaScript Array.of()  function]

 Whenever we need to get elements of an array that time we take the help of the Array.of( ) method in JavaScript. 



    console.log(Array.of(11,21,33));
    console.log(Array.of(0,0,0));
    console.log(Array.of(["Kismat","Amy","Shakeel", "Minto"]));
    console.log(Array.of(1,2,3,"Japan"));
     
    output:
    [ 11, 21, 33 ]
    [ 0, 0, 0 ]
    [ [ 'Kismat', 'Amy', 'Shakeel', 'Minto' ] ]
    [ 1, 2, 3, 'Japan' ]

 

 

 27. JavaScript Array pop() Method

 The arr.pop() method is used to remove the last element of the array and also returns the removed element. This function decreases the length of the array by 1.

 

 
    function popp(){
        let arr = ["Pop","function","JavaScript","Code"];
        let newArr = arr.pop();
        console.log(newArr);
    }
    popp();
   
    output:
            Code

 


    let num = [12,33,44,345,3212];
    let pp = num.pop();
    console.log(num);
    console.log(pp);

    output:
    [ 12, 33, 44, 345 ]
    3212 
 

 

 


    let num = [12,33,44,345,3212];
    num.pop();
    console.log(num);

    output:

    [ 12, 33, 44, 345 ]

 

 


    function fun(){
        let arr = [23,234,567,3];
        let popped = arr.pop();
        console.log(popped);
        console.log(arr);
    }
    fun();
 
    output: 
    3
    [ 23, 234, 567 ]

 


    function arr(){
        let arr = [];
        let new_arr = arr.pop();
        console.log(new_arr);
    }
    arr();
 
    output: undefined

 


 

 28.  JavaScript Array push() Method

 The arr.push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array.

 

 
    function pushh(){
        let arr = ["Lebanon", "Hongkong","Japan","Tokyo"];
        let arr1 = arr.push("New York");
        console.log(arr);
    }
    pushh();
 
    output:
    [ 'Lebanon', 'Hongkong', 'Japan', 'Tokyo', 'New York' ]
 

 

 

 
    function fu(){
        let arr = [323,43,354];
        console.log(arr.push('Coder','Programmer','Developer'));
        console.log(arr);
    }
    fu();
 
    output:  
    6
    [ 323, 43, 354, 'Coder', 'Programmer', 'Developer' ]

 

 

 29. JavaScript Array reduce() Method

 The arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
 
 
 

    var arr = [10,20,30,40,50,60];

    function sumOfArray(sum, num){
        return sum + num;
    }

    function func(item){
        console.log(arr.reduce(sumOfArray));
    }
    func();
     
    output: 210

 
 
 
 
 
    let arr = [1.5,20.3,11.1,40.7];

    function sumOfArray(sum, num){
        return sum + Math.round(num);
    }

    function funn(item){
        console.log(arr.reduce(sumOfArray,0));
    }
    funn();
 
   output: 74
 
 
 
 
 
 
 
 
 

 

 30.  JavaScript Array reduceRight() Method

 The arr.reduceRight() method in JavaScript is used to convert elements of the given array from right to left to a single value.
 


    const num = [175,50,25];

    function subOfArray(total,num){
        return total - num;
    }
    function result(item){
        console.log(num.reduceRight(subOfArray));
    }
    result();
 
    
   output: -200 
 
 
 

    let arr = [10,20,30,40,50,60];

    function subArray(total,num){
        return total - num;
    }

    function fun1(item){
        console.log(arr.reduceRight(subArray));
    }
    fun1();
 
    
   output: -90

 

 

 

 

 31. JavaScript Array reverse() Method

 The arr.reverse() method is used for in-place reversal of the array. The first element of the array becomes the last element and vice versa.
 
 


    const arr = [34,234,567,4];
    console.log(arr);
    const new_arr = arr.reverse();
    console.log(new_arr);
 
    output:  

    [ 34, 234, 567, 4 ]
    [ 4, 567, 234, 34 ]
 

 

 


    function func(){
        let arr =['Portal','Science','Computer','Coder'];
        console.log(arr)

    let new_arr = arr.reverse();
    console.log(new_arr);
    }
    func();
     
    output: 
 
    [ 'Portal', 'Science', 'Computer', 'Coder' ]
    [ 'Coder', 'Computer', 'Science', 'Portal' ]

 

 

 

 

32.  JavaScript Array shift() Method

 The arr.shift() method removes the first element of the array thus reducing the size of the original array by 1.
 
 
    function funNam(){
        let arr = ["London","Turkey","Abu Dhabi","Brunui"];
        let value = arr.shift();
        console.log(value);
        console.log(arr);
    }
    funNam();
 
    output: 
 
    London
    [ 'Turkey', 'Abu Dhabi', 'Brunui' ]


 
    function func(){
        let arrr = [34,234,567,4];
        let value = arrr.shift();
        console.log(value);
        console.log(arrr);
    }
 
    func();
 
    output: 
    34
    [ 234, 567, 4 ]
 

 



    function funcc(){
        let array = [];
        let nwArray = array.shift();
        console.log(nwArray);
    }
    funcc();

 
    output: 
    undefined
 

 

 

33. JavaScript Array slice() Method

 The arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.
 


    function func(){
        let arr = [23,56,87,32,75,13];
        let new_arr = arr.slice(2,4);
        console.log(arr);
        console.log(new_arr);
    }
    func();
 
    output:
    [ 23, 56, 87, 32, 75, 13 ]
    [ 87, 32 ]

 


    let arr = [23,56,87,32,75,13];
    let new_arr = arr.slice(2);
    console.log(arr);
    console.log(new_arr);

    output:
    [ 23, 56, 87, 32, 75, 13 ]
    [ 87, 32, 75, 13 ]
 

 

 

        let arr = [23,56,87,32,75,13];
        let new_arr = arr.slice();
        console.log(arr);
        console.log(new_arr);

    output:
    [ 23, 56, 87, 32, 75, 13 ]
    [ 23, 56, 87, 32, 75, 13 ] 
 

 

 

 

34.  JavaScript Array some() Method

 The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.

 


    function checkAvailabity(arr,val){
        return arr.some(function (arrVal) {
            return val === arrVal;
        })
    }
    function func(){
        let arr = [2,5,8,1,4]
        console.log(checkAvailabity(arr,2));
        console.log(checkAvailabity(arr,87))
    }
    func();
    
    output:
    true
    false
 

 



    let arr = [2,5,8,1,4];

    function checkAvailability(arr,val){
        return arr.some(function(arrVal){
            return val === arrVal;
        })
    }
    console.log(checkAvailability(arr,2));
    console.log(checkAvailability(arr,87));
    
    output:
    true
    false

 


        function isGreterThan5(element, index,array){
            return element > 5;
        }
        function func(){
            let arr = [2,4,8,1,4];
            let value = arr.some(isGreterThan5)
            console.log(value);
        }
        func();
     
    output:     
    true

 


    function isGreterThan5(element,index,array){
        return element > 5;
    }
    function func(){
        let array = [-2,5,3,1,4];
        let value = array.some(isGreterThan5)
        console.log(value)
    }
    func();

     
    output: false 
 

 

 

 

 35. JavaScript Array sort() Method

 The arr.sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order.
 

    function func(){
        let arr = ["Geeks","for","Coder"];
        console.log(arr);
        console.log(arr.sort());
    }
    func();
 
    output:
    [ 'Geeks', 'for', 'Coder' ]
    [ 'Coder', 'Geeks', 'for' ]

 


    const arr = [2,5,7,1,4];
    console.log(arr);
    console.log(arr.sort());
    
    output:
    [ 2, 5, 7, 1, 4 ]
    [ 1, 2, 4, 5, 7 ]
 

 

 
    const arr = [2,5,8,1,4];
    console.log(arr.sort(function (a,b){
        return a + b * 2;
    }));
    console.log(arr);

    output:
    [ 2, 5, 8, 1, 4 ]
    [ 2, 5, 8, 1, 4 ]

 

 
    function func(){
        let arr = [2,5,8,1,4];

    console.log(arr.sort());
    console.log(arr);
    };
    func();
 
    output:  
    [ 1, 2, 4, 5, 8 ]
    [ 1, 2, 4, 5, 8 ]

 


        function func() {
   
            // Original array
            var arr = [2, 5, 8, 1, 4];
       
            console.log(arr.sort(function(a, b) {
            return a + 2 * b;
        }));
        console.log(arr);
        }
        func();
 
 
    output:
    [ 2, 5, 8, 1, 4 ]
    [ 2, 5, 8, 1, 4 ]
 

 

 

 

 36. JavaScript Array splice() Method

 The arr.splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

 


    var webDvlop = ["HTML", "CSS", "JS", "Bootstrap"];
    console.log(webDvlop);

    // Add 'React_Native' and 'Php' after removing 'JS'.
    var removed = webDvlop.splice(2, 1, 'PHP', 'React_Native')

    // No Removing only Insertion from 2nd
    // index from the ending
    webDvlop.splice(-2, 0, 'React');
 
    output: 
    [ 'HTML', 'CSS', 'JS', 'Bootstrap' ]
 

 


    var languages = ['C++', 'Java', 'Html', 'Python', 'C'];
   
    console.log(languages);
   
    // Add 'Julia' and 'Php' after removing 'Html'.
    var removed = languages.splice(2, 1, 'Julia', 'Php')

   
    // No Removing only Insertion from 2nd index from the ending
    languages.splice(-2, 0, 'Pascal')
    console.log(languages)
 
    output: 
 
    [ 'C++', 'Java', 'Html', 'Python', 'C' ]
    [
      'C++',    'Java',
     'Julia',  'Php',
      'Pascal', 'Python',
      'C'
    ]
 

 

 

 37.  JavaScript | array .toLocaleString()  function

 The array.toLocaleString() is an inbuilt function in JavaScript which is basically used to convert the element of the given array to string. 


 


    var name = "geeksforgeeks";
    var number = 567;
   
    // It will give current date and time.
    var date = new Date();
   
    // Here A is an array containing elements of above variables.
    var A = [ name, number, date ];
   
    // applying array.toLocaleString function.
    var string = A.toLocaleString();
   
    // printing string.
    console.log(string);
 
 
    output:
    geeksforgeeks,567,4/9/2022, 10:55:25 PM
 

 

 

    var name = [ "Ram", "Sheeta", "Geeta" ];
    var number1 = 3.45;
    var number2 = [ 23, 34, 54 ];
   
    // Here A is an array containing elements of above variables.
    var A = [ name, number1, number2 ];
   
    // applying array.toLocaleString function.
    var string = A.toLocaleString();
   
    // printing string.
    console.log(string);
     
    output: 
    Ram,Sheeta,Geeta,3.45,23,34,54
 

 

 

 

 38. JavaScript Array toString() Method

 The arr.toString() method returns the string representation of the array elements.


    function func() {
   
        // Original array
        var arr = ["Geeks", "for", "Geeks"];
   
        // Creating a string
        var str = arr.toString();
    console.log(str);
    }
    func();
 
    output:
    Geeks,for,Geeks
 

 


    function func() {
   
        // Original array
        var arr = [2, 5, 8, 1, 4];
   
        // Creating a string
        var str = arr.toString();
        console.log(str);
    }
    func();
 
    output:
    2,5,8,1,4
 

 

 

 

 39.  JavaScript Array unshift() Method

 The arr.unshift() method is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array.


    function func() {
       
        // Original array
        var array = ["GFG", "Geeks", "for", "Geeks"];
   
        // Checking for condition in array
        var value = array.unshift("GeeksforGeeks");
   
        console.log(value);
        console.log(array);
    }
   
    func();
 
    output: 
    5
    [ 'GeeksforGeeks', 'GFG', 'Geeks', 'for',
 

 


    var arr = [23,76,19,94];
    console.log(arr.unshift());
    console.log(arr);
 
    output:  
    4
    [ 23, 76, 19, 94 ]
 

 


    function sayHello() {
        var arr = [23,76,19,94];
       
        // Adding elements to the front of the array
        console.log(arr.unshift(28,65));
        console.log(arr);
    }
    sayHello();
 
    output:
    6
    [ 28, 65, 23, 76, 19, 94 ]
  

 


    function sayHello() {
        var arr = [23,76,19,94];
       
        // Adding elements to the front of the array
        console.log(arr.unshift(28,65));
        console.log(arr);
    }
    sayHello();
 
    output:  
    6
    [ 28, 65, 23, 76, 19, 94 ]
 
 

إرسال تعليق (0)
أحدث أقدم