Create array of objects in javascript LEARNOVITA

JavaScript Arrays Tutorial | Complete Beginner’s Guide

Last updated on 11th Aug 2022, Blog, Tutorials

About author

Avinash Tripathi (JavaScript Developer )

Avinash Tripathi has extensive knowledge of Java, Core Java, Spring, J2EE, Struts, and Hibernate. His articles aid students in acquiring Domain-specific knowledge.

(5.0) | 19578 Ratings 2065

Introduction

Node.js provides AN Array object for assortment manipulation. In general, a Node.js Array object has an equivalent behavior with a JavaScript Array object. during this section, we tend to ar about to manipulate AN Array object in Node.js.

Creating AN Array Object

There are 3 ways to make AN Array object. the primary issolely by typewriting the array object.

  • var array = [ ];

Option 2 is to make AN Array object by instantiating the Array object.

  • var array = new Array( );

The last choice is to make AN Array object by inserting assortment information.

  • var array = [3,5,12,8,7];

Inserting information

After making AN Array object, we will insert information. Use [] with index if you would like to assign the worth.

  • array[0] = 3;
  • array[1] = 5;
  • array[2] = 12;
  • array[3] = 8;
  • array[4] = 7;
  • array.push(10);
  • array.push(18);

You can additionally use the push() operate to insert information.

Accessing information

To access array information, you’ll use [] with information index parameter.

  • // show information
  • console.log(array);
  • for(var i=0;i

Updating knowledge

To update associate degree item of array knowledge, you’ll use [] with knowledge index and so assign a replacement price.

  • // edit
  • array[2] = -2;
  • array[3] = 5;
  • console.log(array);

Removing knowledge

You can use the pop() operate to get rid of knowledge from the Array. If you would like to get rid of knowledge by specific index then you’ll use the splice()function.

The following may be a sample script for removing data:

  • // take away knowledge
  • array.pop();
  • array.pop();
  • // take away knowledge by index
  • var index = 1;
  • array.splice(index,1);
  • console.log(array);

Types of Array in Java

In Java, there are two types of arrays:

    1. 1.Single-Dimensional Array
    2. 2.Multi-Dimensional Array

1.Single Dimensional Array

A one dimensional array is one that only contains one subscript or dimension. It is merely a collection of variables with the same data type.Multiple rows and one column or one row and many columns can make up a one-dimensional array. A student’s grades across five subjects, for instance, provide a one-dimensional array.

Example:

  • int marks[ ] = {56, 98, 77, 89, 99};

JVM (Java Virtual Machine) will construct five blocks at five separate memory locations when the aforementioned line is executed. representing marks[0], marks[1], marks[2], marks[3], and marks[4].By first defining an array and then allocating memory with the new keyword, we may also build a one-dimensional array.Example:

  • int marks[ ];// declared an array
  • marks = new int[5]; // allocating memory
  • // initializing array using index
  • marks[0] = 56;
  • marks[1] = 98;
  • marks[2] = 77;
  • marks[3] = 89;
  • marks[4] = 99

Let’s examine how a single-dimensional array can be implemented in Java.

  • public class Demo {
  • public static void main (String[ ] args) {
  • // declaring and initializing an array
  • String strArray[ ] = {“Python”, “Java”, “C++”, “C”, “PHP”};
  • // using a for-each loop for printing the array
  • for(String i : strArray) {
  • System.out.print(i + ” “);
  • }
  • // find the length of an array
  • System.out.println(“\nLength of array: “+strArray.length);
  • }
  • }

Output:

Python Java C++ C PHP

Length of array: 5

In the previous sample code, a single-dimensional array called strArray was constructed. It has a single row and numerous columns.

2.Multi-Dimensional Array

We don’t always use a single-dimensional array. We may need to build an array inside of another array.

Let’s say we need to create a programme that keeps track of 60 students’ grades in five different areas. In this instance, all that is required is to create 60 five-dimensional one-dimensional arrays, which will subsequently be combined into a single array. In light of this, we can create a 2D array with five columns and sixty rows.

An array of arrays that represents numerous rows and columns is all that makes up a multi-dimensional array. There are nD, 3D, and 2D types of these arrays. This kind of array can be used to represent 2D data such as tables and matrices.

Instead of using one square bracket, a multi-dimensional array needs to have two.Example:

  • int marks[ ][ ] = {
  • {77,85,68,99,87},
  • {98,56,79,90,92},
  • {78,88,56,70,99}
  • };

Let’s use the well-known Matrix multiplication example to better comprehend a multi-dimensional array now.

  • public class Demo {
  • public static void main (String[] args) {
  • // declaring and initializing arrays
  • int arr1[ ][ ] = {{1,2,3},{4,5,6},{7,8,9}};
  • int arr2[ ][ ] = {{2,2,2},{2,2,2},{2,2,2}};
  • // Printing Array1 in matrix format
  • System.out.println(“Array1 -“);
  • for(int i=0;i<3;i++) { // for-loop for number of rows
  • for(int j=0;j<3;j++) { // for-loop for number of columns
  • System.out.print(arr1[i][j] + ” “);
  • }
  • System.out.println();
  • }
  • // Printing Array2 in matrix format
  • System.out.println(“Array2 -“);
  • for(int i=0;i<3;i++) { // for-loop for number of rows
  • for(int j=0;j<3;j++) { // for-loop for number of columns
  • System.out.print(arr2[i][j] + ” “);
  • }
  • System.out.println();
  • }
  • // creating another array with the same dimensions to store the result
  • int arr3[ ][ ] = new int[3][3];
  • // Multiplying arr1 and arr2, storing results in arr3
  • System.out.println(“Multiplication of Array1 and Array2 – “);
  • for(int i=0;i<"arr1.length;i++"") {
  • for(int j=0;j<"arr2.length;j++")" {
  • arr3[i][j] = 0;
  • for(int k=0;k<"arr3.length;k++"") {
  • arr3[i][j] += arr1[i][k] * arr2[k][j];
  • }
  • System.out.print(arr3[i][j] + ” “);
  • }
  • System.out.println();
  • }
  • }
  • }
  • Output:
  • Array1 –
  • 1 2 3
  • 4 5 6
  • 7 8 9
  • Array2 –
  • 2 2 2
  • 2 2 2
  • 2 2 2
  • Multiplication of Array1 and Array2 –
  • 12 12 12
  • 30 30 30
  • 48 48 48

One well-known application of a 2D array is matrix multiplication. Two 3×3-dimensional arrays were declared in the code aforementioned. Then, to store the outcome, we made another array with the same size. Later, we put matrix multiplication logic into practise.

Create an Array

An array can be made in one of two ways:

1.Using a literal array

The use of an array literal is the simplest approach to generate an array. []. For example,

  • const array1 = [“eat”, “sleep”];

2.Utilizing the fresh keyword

Arrays can also be created in JavaScript by using the new keyword.

  • const array2 = new Array(“eat”, “sleep”);
  • In both of the above examples, we have created an array having two elements.
  • // empty array
  • const myList = [ ];
  • // array of numbers
  • const numberArray = [ 2, 4, 6, 8];
  • // array of strings
  • const stringArray = [ ‘eat’, ‘work’, ‘sleep’];
  • // array with mixed data types
  • const newData = [‘work’, ‘exercise’, 1, true];
  • Arrays, functions, and other objects can all be stored inside of them. For instance,
  • const newData = [
  • {‘task1’: ‘exercise’},
  • [1, 2 ,3],
  • function hello() { console.log(‘hello’)}
  • ];

Access Elements of an Array

Individual items in an array can be accessed by using numerical indexes (like 0, 1, 2,…). Const myArray = [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]; is an example of this.,

  • const myArray = [‘h’, ‘e’, ‘l’, ‘l’, ‘o’];
  • // first element
  • console.log(myArray[0]); // “h”
  • // second element
  • console.log(myArray[1]); // “e”
  • Run Code

Array length

Using the length property, the number of items in an array can be determined. I’ll give you an example:

  • const dailyActivities = [ ‘eat’, ‘sleep’];
  • // this gives the total number of elements in an array
  • console.log(dailyActivities.length); // 2

Array Methods:

Different array methods in JavaScript simplify practical computations.

Example: JavaScript Array Methods

  • let dailyActivities = [‘sleep’, ‘work’, ‘exercise’]
  • let newRoutine = [‘eat’];
  • // sorting elements in the alphabetical order
  • dailyActivities.sort();
  • console.log(dailyActivities); // [‘exercise’, ‘sleep’, ‘work’]
  • //finding the index position of string
  • const position = dailyActivities.indexOf(‘work’);
  • console.log(position); // 2
  • // slicing the array elements
  • const newDailyActivities = dailyActivities.slice(1);
  • console.log(newDailyActivities); // [ ‘sleep’, ‘work’]
  • // concatenating two arrays
  • const routine = dailyActivities.concat(newRoutine);
  • console.log(routine); // [“exercise”, “sleep”, “work”, “eat”]concat(newRoutine);
  • Run Code

Working of JavaScript Arrays

Arrays are treated as objects in JavaScript. Array indices also serve as object keys.Arrays themselves are objects, therefore their constituent parts are also reference-stored. If you make a change to the copied array, it will be reflected in the original array when you do a value copy. I’ll give you an example:

  • let arr = [‘h’, ‘e’];
  • let arr1 = arr;
  • arr1.push(‘l’);
  • console.log(arr); // [“h”, “e”, “l”]
  • console.log(arr1); // [“h”, “e”, “l”]
  • Run Code
  • You can also use an array to store values and then retrieve them using a key.
  • let arr = [‘h’, ‘e’];
  • arr.name = ‘John’;
  • console.log(arr); // [“h”, “e”]
  • console.log(arr.name); // “John”
  • console.log(arr[‘name’]); // “John”
  • Run Code

It is not advised, however, to save values by passing in a list of random names.For this reason, an array is the appropriate data structure to employ if the items you’re working with are arranged in some kind of hierarchy in JavaScript. If you can avoid it, though, objects are the way to go.

Are you looking training with Right Jobs?

Contact Us

Popular Courses