jquery array Basics- All about jquery Arrays Best Example and Demo – Top 10+ PHP functions

In jquery array, what is array? : A group of identical data is called an array. Which are stored in the memory location of the computer in sequence. It is a type of data structure in which work can be done very easily with the data kept.

what is an array? Array is a data structure which is a set of elements that contain the same data and the same name. They are commonly used to organize data in computer programs so that any set of similar values can be easily sorted and searched.

It always starts with their index value and any array has multiple index values 0 to n-1.

Array data structure is used to store a group of data objects.

jquery array – types of arrays

types of arrays

Arrays are of the following three types:-

  • one dimensional arrays.
  • two dimensional arrays.
  • Multi dimensional arrays.

javascript interview questions

1:- one dimensional(1-D) arrays:-

Arrays that contain only one subscript are called one-dimensional arrays. It is used to store data in linear form.

2:- two dimensional(2-D) arrays:-

The arrays in which there are two subscripts are called two dimensional arrays. Two dimensional arrays are also called matrix and table.

3:- Multi dimensional(M-D) arrays:–

The arrays which contain more than two subscripts are called Muti-dimensional arrays.

Applications of Array

  • They are used to implement mathematical vectors and matrices.
  • They are used to implement rectangular tables.
  • Arrays are used to implement Heaps, Hash, Tables, Deques, Queues, Stacks and Strings.
  • They are used as a compact alternative to multiple statements to determine the complete or partial control flow of a program.

Types of Indexing in array

  • 0 (Zero Based Indexing)
  • 1 (One Based Indexing)
  • n (n–Based Indexing)

Advantages of Array

  • It stores the same type of data.
  • We only have to remember the first index of the array.
  • It is also used to implement elements like Stack, Graph, Queue.
  • Multiple values can be easily stored in this.

Disadvantages of Array

  • The time complexity increases in inserting and deleting any operation.
  • It is fixed in size, due to which the problem of memory wastage also arises.
  • If you have enough space in your memory but it is not in contiguous form then you cannot initialize the array.
  • In this, once you choose the size of the array, then you cannot edit it later.

array in javascript & jquery array

It’s a special variable.

var fruits = ["Apple", "Banana", "Mango"];

Access the Elements of an Array

<p id="demo"></p>

<script>
var fruits = ["Apple", "Banana", "Mango"];
document.getElementById("demo").innerHTML = fruits[0];
</script>

1. print array in jquery

<script>
    $(document).ready(function(){
        var fruitsArray = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
        $.each(fruitsArray, function(index, value){
            $("#result").append(index + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="result"></div>
</body>

2. print object in jquery

JSON.stringify(rows)

jquery array

<script>
    $(document).ready(function(){
        var supercarObject = {"brand": "Apple", "model" : "Orange", "origin": "Pineapple"};
        $.each(supercarObject, function(key, value){
            $("#result").append(key + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="result"></div>
</body>

jquery array: Print array and object

<html>
<head>
<title>jQuery: Print array and object</title>
<script src="jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery(document).ready(function(){				
		var fruits = [ "Apple", "Banana", "Orange", "Mango", "Pineapple" ];
		var obj = { one:"Apple", two:"Banana", three:"Orange", four:"Mango", five:"Pineapple" };
		
		jQuery.each(fruits, function(i, val) {
		  $("#fruits").append(i + " : " + val + "<br/>");		  
		});
		
		jQuery.each(obj, function(i, val) {
		  $("#objData").append(i + " => " + val + "<br/>");
		});
	});
</script>
</head>
<body>
<div id="fruits">
<strong>Array</strong><br/>

</div>

<div id="objData">
<strong>Object</strong><br/>

</div>
</body>
</html>

declare array in jquery

Declare Array using jquery array

var DataList=[];  

Declare and Initialize JS Array

var stringArray = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];

var numericArray = [1, 2, 3, 4];

var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];

arrays

ArrayList in jQuery

fruits.push({  
   Id:1,  
   Name: Orange  
});  
fruits.push({
   Id:2,
   Name:Orange
});

Assigning valus at the time of declaration in Array

var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];  
var number=["1","2","3","4"];

Assigning values at the time of declaration in ArrayList

fruits=[{      
   Id:1,      
   Name:Orange      
}    
{Id:2,    
   Name:XYZ    
}];    

Assigning values in ArrayList using for Loop

var Ids=1;    
var naming="Orange";    
for(var i=0;i<fruits.length;i++)    
{    
    Ids=fruits[i].Id;    
   naming=fruits[i].Name;    
}   

How to split string to array by comma using jquery?

“jquery split string to array”

<!DOCTYPE html>
<html>
<head>
    <title>How to split string to array by comma using jquery? - pakainfo.com</title>
</head>
<body>
  
<script type="text/javascript">
   
    var fruits = "A,B,C,C,D,E,F,G,H";
   
    console.log(fruits.split(','));    
   
</script>
</body>
</html>

jquery split string to array
using javascript explode

//split into array of strings.
var fruits = "Well, Mango, Banana , we , Orange, Pineapple";
var res = fruits.split(",");

jquery each json array

var myDb = {
    "04c85ccab52880": {
        "name": "name1",
        "firstname": "fname1",
        "societe": "soc1"
    },
    "04c95ccab52880": {
        "name": "name2",
        "firstname": "fname2",
        "societe": "soc2"
    },
    "048574220e2a80": {
        "name": "name3",
        "firstname": "fname3",
        "societe": "soc3"
     }
};
var arr = [];

$.each( myDb, function( key, value ) {
    //arr.push( value );    
    console.log("key => "+key);
    $.each( value, function( ky, val ) {
        console.log('ky => '+ky);
        console.log('val => '+val);
    });    
});

array in jquery

1. Loop

<script type='text/javascript'>

var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
 
function checkValue(value,fruits){
  var status = 'Not exist';
 
  for(var i=0; i<fruits.length; i++){
    var name = fruits[i];
    if(name == value){
      status = 'Exist';
      break;
    }
  }

  return status;
}
console.log('status : ' + checkValue('Banana', fruits) );
console.log('status : ' + checkValue('Orange', fruits) );
</script>

2. Array.indexOf()

<script type='text/javascript'>
var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
var text = "Sonarika Bhadoria";

// Search in Array
console.log( 'Index : ' + fruits.indexOf('Mango') );
console.log( 'Index : ' + fruits.indexOf('Pineapple') );

// Search in String
console.log( 'Index : ' + text.indexOf('a') );

</script>

3. jQuery.inArray()

<script type='text/javascript'>
var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
var text = "Orange Baka";
// Searching in Array
console.log( 'Index : ' + jQuery.inArray('Mango', fruits) );
console.log( 'Index : ' + jQuery.inArray('Pineapple', fruits ));
 
// Searching in String variable
console.log( 'Index : ' + jQuery.inArray( "e", text ));

</script>

convert string to array in jquery

“jquery convert a string to an array”

var fruits = "1,2,3,4,5,6";
var numbersArray = fruits.split(',');

jquery string to array

//split into array of strings.
var fruits = "Pineapple, how, Banana , Orange , Apple, Mango";
var res = fruits.split(",");

string split javascript

var fruits = "An,Orange,in,a,Banana,Mango,Apple,a,Pineapple";
var fruits = fruits.split(",");

js string to array

var fruits = 'Apple,Orange';
var MyArray = fruits.split(',');//splits the text up in chunks

How to Convert a JS Object to an Array Using jQuery?

“jquery object to array”

<script>
    var myObj = {
        name: "Orange",
        age: 28,
        gender: "Male",
        email: "[email protected]"
    };
    
    // Converting JS object to an array
    var fruits = $.map(myObj, function(value, index){
        return [value];
    });
    
    console.log(fruits);
    // Prints: ["Orange", 28, "Male", "[email protected]"]
</script>

Jquery – How to remove empty or null values from array?

“remove value from array jquery”

<!DOCTYPE html>
<html>
<head>
    <title>jquery array - How to remove empty or null values from array? - Pakainfo.com</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
   
<script type="text/javascript">
  var fruits = ["Orange", "Banana", "Mango", "", "Pineapple", null, "Apple"];

  var fruitsNew = fruits.filter(function (el) {
    return el != null && el != "";
  });
  
  console.log(fruitsNew);
  
</script>
   
</body>
</html>

How to Loop through an Array/Object in jQuery?

“jquery each json array”

var fruits = [
               {
                  "id": "007",
                  "agent": "Mango"
               },                  
               {
                  "id": "006",
                  "agent": "Pineapple"
               }
             ]
// iterate over the JSON array
$.each(fruits , function(index, item) { 
    console.log("fruits Id: " + item.id);
    console.log("fruits Name: " + item.agent);
});

associative array in jquery

“make associative array jquery”

var fruitsDetail = [];
fruitsDetail[0] = "Mango";
fruitsDetail[1] = "Apple";
fruitsDetail[2] = 24;
fruitsDetail[3] = 'Banana';
var x = fruitsDetail.length;     // fruitsDetail.length will return 4
var y = fruitsDetail[1];   

array loop in jquery

array iteration

jQuery.each(array, function(Integer index, Object value){});

object iteration

jQuery.each(object, function(string propertyName, object propertyValue){});

var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) { 
  console.log(index, val)
});

var myObj = { fruitName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
  console.log(propName, propVal);
});

Jquery check if value exists in Array Example

“inarray in jquery”

<!DOCTYPE html>
<html>
<head>
    <title>jquery array check if value exists in Array Example - pakainfo.com</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
</head>
<body>
   
<script type="text/javascript">
   
    var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
   
    console.log($.inArray('Banana', fruits));
   
    if ($.inArray('Banana', fruits) >= 0) {
      console.log('Banana is exist!');
    }else {
      console.log('Banana does not exist!');
    }
   
</script>
</body>
</html>

how to send array in ajax?

How to send array to php script file using ajax?

Read Also:  String Methods List using JavaScript Example

index.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).on('click','#save',function(e) {
    	var fruits = [];
		/*Initializing array with Checkbox checked values*/
        $("input[name='fruits']:checked").each(function(){
            fruits.push(this.value);
        });
    $.ajax({
         data:  {
			 fruits:fruits
		 },
         type: "post",
         url: "save.php",
         success: function(data){
              alert(data);
         }
	});
});
</script>
</head>
<body>
	<form action="" id="form-search">
	  	<input type="checkbox" name="fruits" value="Banana"> I have a Banana<br>
		<input type="checkbox" name="fruits" value="Pineapple"> I have a Pineapple<br>
		<input type="checkbox" name="fruits" value="Orange"> I have a Orange<br>
	</form>
	<button id="save" name="save">Serialize form values</button>
</body>
</html>

save.php

<?php
    $fruits=$_POST['fruits'];
    print_r($fruits);
?>

how to create array in jquery?

Creating an Array using jquery array

  <script> 
   $(document).ready(function() {
    $("button").click(function(){
   var array = $.makeArray(document.getElementsByTagName("li"));  
      // $.makeArray() is to convert an object into an array
   array.reverse(); // reverse the array
   $(array).appendTo(".box");  // display data
    });
  });
  </script>

Example: Searching an Array

 <script> 
   $(document).ready(function() {
    $("button").click(function(){
   var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
      
      $("#demoArray").html("Planet Array : <b>" + fruits);  // display planet array
      
   $("i:eq(0)").text($.inArray("Apple", fruits)); // search array for Apple
   $("i:eq(1)").text($.inArray("Pineapple", fruits));   // search array for Pineapple
   $("i:eq(2)").text($.inArray("Mango", fruits));  // search array for Mango
   $("i:eq(3)").text($.inArray("Orange", fruits)); // search array for Orange
      
    });
});
 </script>

jQuery Array Filtering an Array

  <script> 
   $(document).ready(function() {
    $("button").click(function(){
   var numbers = [1, 2, 3, 4, 5, 6, 7];
      $("#fruits1").text("Original Array:" + numbers.join(","));
      numbers = $.grep(numbers, function(n,i)  // fruits array based on function
      {
       return(i>2);
      });
      $("#fruits2").text("Filtered Array (index > 2):" + numbers.join(","));
      numbers = $.grep(numbers, function(n)
      {
        return (n!=6);
      });
  $("#fruits3").text("Filtering the above Filtered Array (index != 6):" 
                    + numbers.join(" , "));
      
    });
});
 
   </script>

Eliminate Duplicate Elements from Arrays

  <script> 
   $(document).ready(function() {
    $("button").click(function(){
    var divElem = $("div").get(); 

    divElem = divElem.concat($(".copy").get());
      $("div:eq(1)").html("Div Elements before using Unique --- <b>" + divElem.length + "</b> elements.");

      divElem = jQuery.unique(divElem);
      // $.unique() to create a copy of an array with duplicate elements removed
      
      $("div:eq(2)").html("Div Elements after using Unique --- <b>" + divElem.length + "</b> elements.")
                  
      
    });
});
 
   </script>

how to get array value in jquery?

Declare array like following in javascript

<!doctype html>  
<html lang="en">  
<head>  
    <meta charset="utf-8">  
    <title>click demo</title>       
    <!-- Declare Jquery -->  
    <script src="Scripts/jquery-1.10.2.min.js"></script>  
    <script src="Scripts/jquery-1.10.2.js"></script>  
    <title></title>  
    <script type="text/javascript">  
        // Specify a function to execute when the DOM is fully loaded  
        $(document).ready(function ()  
        {  
            // Call button click event  
            $("#btnTest").click(function ()              
            {  
                // Declare array  
                var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];  
                // Define jquery each loop to get value of array  
                $.each(fruits, function (index, value)  
                {  
                    // Get value in alert  
                    alert(value);  
                });  
            });  
        });  
    </script>     
</head>  
<body>  
    <input type="button" id="btnTest" value="GetValuefromArray" />    
</body>  
</html>  

how to get multiple checkbox value in jquery using array?

“jquery multiple checkboxes array”

var checked = []
$("input[name='options[]']:checked").each(function ()
{
    checked.push(parseInt($(this).val()));
});

how to declare array in jquery?

jQuery is a JavaScript library, not a language.

var fruits = [1, 2, 3, 4, 5];

1. how to take create array using jquery

var length = 5;
var array = [];
var i = 0;

for (i = 0; i != length; i++){
  array.push(i)
  //array.push is used to push a value inside array
} 

console.log(array);

2. jquery create array

var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];

/*// OUTPUT
---------------------------*/
console.log(fruits[1]); // Outputs 'Apple'

how to check array is empty or not in jquery?

In jquery array: “jquery check array empty”

Read Also:  javascript redirect to relative url with parameters

1. if array is empty jquery

var fruits = [];

if (fruits.length === 0) {
    // Your source code jquery array
}

2. javascript not empty array not string

if (Array.isArray(fruits) && fruits.length) {
    // fruits exists and is not empty
}

3. js how to check is array empty es6

var fruits=[];
if(!fruits.length){
	// I am empty
}else{
	// I am not empty
}

how to define array in jquery?

jquery array: Declare Arrays in jQuery

Read Also:  get multiple checkbox value in jquery

Declare an array (using the array constructor)

var fruits1 = new Array();
var fruits2 = new Array("Apple", "Banana", "Orange", "Mango", "Pineapple");

Declare an array (using literal notation)

var fruits1 = [];
var fruits2 = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];

Create an array from a method’s return value

var carter = "I-learn-JavaScript";
var fruits3 = carter.split("-");

Declare an empty array using literal notation:

var fruits = [];

The variable now contains an array of length zero

How to display all items or values in an array using loop in jQuery?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Print Array Values with Loop - jquery array</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var fruitsArray = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
        $.each(fruitsArray, function(index, value){
            $("#result").append(index + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="result"></div>
</body>
</html>

How to check if array is empty or null or undefined in javascript?

<!DOCTYPE html>
<html>
<head>
    <title>How to check if array is empty or null or undefined in jquery array? - Pakainfo.com</title>
</head>
<body>
  
<script type="text/javascript">
   
    var fruits = [1, 2, 3];
  
    if (fruits && fruits.length > 0) {
        console.log('fruits is not empty.');
    }else{
        console.log('fruits is empty.');
    }
  
  
    var fruits2 = [];
  
    if (fruits2 && fruits2.length > 0) {
        console.log('fruits2 is not empty.');
    }else{
        console.log('fruits2 is empty.');
    }
  
  
    if (typeof fruits3 !== 'undefined' && fruits3.length > 0) {
        console.log('fruits3 is not empty.');
    }else{
        console.log('fruits3 is empty.');
    }
  
  
    var fruits4 = null;
   
    if (fruits4 && fruits4.length > 0) {
        console.log('fruits4 is not empty.');
    }else{
        console.log('fruits4 is empty.');
    }
   
</script>
</body>
</html>

How to Get Multiple Checkbox Value in jQuery Using Array?

using :checked selector in jquery array

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jquery array- Get Multiple Checkbox Value in jQuery</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
    <form>
        <h3>Select your favorite fruits:</h3>
        <label><input type="checkbox" value="Apple" name="fruit"> Apple</label>
        <label><input type="checkbox" value="Banana" name="fruit"> Banana</label>
        <label><input type="checkbox" value="Orange" name="fruit"> Orange</label>
        <label><input type="checkbox" value="Mango" name="fruit"> Mango</label>
        <label><input type="checkbox" value="Pineapple" name="fruit"> Pineapple</label>
        <br>
        <button type="button">Get Selected Values</button>
    </form>
  <script>
      $(document).ready(function() {
          $("button").click(function(){
              var fruits = [];
              $.each($("input[name='fruit']:checked"), function(){
                  fruits.push($(this).val());
              });
              alert("Your favourite fruits are: " + fruits.join(", "));
          });
      });
  </script>
</body>
</html>

JQuery – How to push specific key and value in array?

<!DOCTYPE html>
<html>
<head>
    <title>jquery array - How to push specific key and value in array? - pakainfo.com</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    
<script type="text/javascript">
    
    var fruits = [
        { "id" : "1", "fruitName" : "Apple", "lastName" : "A36589" }, 
        { "id" : "2", "fruitName" : "Banana", "lastName" : "B898989" }, 
        { "id" : "3", "fruitName" : "Orange", "lastName" : "O8787878" }, 
        { "id" : "4", "fruitName" : "Mango", "lastName" : "M989898" }
      ];
   
      var myObj = {};
  
      $.each(fruits, function (i, value) {
          myObj[value.id] = value.fruitName;
      });  
   
      console.log(myObj);
    
</script>
   
</body>
</html>

Also Read : jQuery Multidimensional Array name selector

How can I create and access multidimensional arrays in jquery array?

<script>
    $(function () {
        var fruits = [];
        fruits[0] = [1, 2, 3]; 
        fruits[1] = [4, 5, 6];
        fruits[2] = [7, 8, 9];
 
        console.log(fruits);
        console.log(fruits[0][0]); 
        console.log(fruits[1][2]);
    });
</script><br>