Array object in javascript example

Javascript array object: how to use it Methods?

The JavaScript Array class is a global object that is used in the construction of arrays. In Javascript, Arrays are listed like objects, and are remarkable flexibility. We can easily, sort, add, and remove items according to their position.

Javascript Array object

In Javascript array is a type of object that is used to store multiple values in a single variable. Each value has a numeric index that may contain data of any data type Booleans, numbers, strings, functions, objects, and even another array.

Syntax of Javascript Array object

 const framworks = ['Angular', 'React', 'Vue']

How to create Javascript array object

const myArray = new Array(); // Empty object const myArray = [];

Initializing an Array

In the previous example code for creating an array, we have an empty array. We can assign data to an array object while creating it.

const pLanguages = ['C', 'Javascript', 'Java']; const pLanguages = new Array("C", "Javascript", "Java", "C++");

We can add array data after an array object is created.

const pLanguages = []; pLanguages[0] = 'C'; pLanguages[1] = 'Javascript'; pLanguages[2] = 'Java'; pLanguages[3] = 'C++';

Javascript array object example

Javascript Array object properties

  • length: We can length property on arrayObject name to get a length of an array. As for our example, pLanguages.length will return integer 4.
  • index: As in another programming, the array index starts at zero to get the individual item in the array we can use an index as follow. pLanguages[1] and 1 is the index.
  • constructor: Is the reference to array function which used to create array object.
  • prototype: We can see in the previous image a prototype of the array object, and it has a list of objects and properties.

Javascript array object looping its items

We can loop javascript array objects using for loop and forEach loop. In this example, we are using forEach on the array object.

const pLanguages = ['C', 'Javascript', 'Java']; pLanguages.forEach((item, index) => < console.log('Index :' +index + ' ' + item); >); Output: Index 0 : C Index 1 : Javascript Index 2 : Java

In the forEach loop, we pass each item with an index in function to print its value. Where item represents an element of an array at a particular moment and index is the index value of an element.

Javascript object methods

Javascript array has lots of pre-made methods which are ready to use, we can use this method to perform a variety of activities like sorting, adding items, removing items, and more. Here we had listed some of the most common methods used on Javascript array objects.

In this example, we are removing one element at the second index and adding two new an element at companies array index 2. The resulting array element of companies is Apple, Google, Infosys, TCL, and IBM, and where second element Facebook is removed from an array list.

Читайте также:  Управление пользователями php mysql

Example 2: Here we are removing the element from the existing array and adding the removed element to a new array called sliced.

 

Click the button to add and remove elements.

The output of the above code, oldArray :[ “zero”, ”one”] and new sliced: “[two”, ”three”].

Javascript object methods find() example

Javascript array object to find an element using its element property. In our next example, we have an array object containing a list array object in it. Here is an array of array object countries, each element in the countries contains an array object.

const countries = [ < name: "France", area: 640679, population: 64979548, >, < name: "India", area: 3287263, "population": 1324171354, >, < name: "Germany", area: 357114, population: 82114224, >, < name: 'Canada', area: 9976140, population: 36624199 >, < name: 'United States', area: 9629091, population: 324459463 >];

Let’s used the find method to find detailed information about the country India using its name.

Javascript object methods – find

let country = countries.find(item => item.name === "India"); let temp = `Name : $ < country.name > 
Area : $ < country.area >
Population : $< country.population >`; document.getElementById("demo").innerHTML = temp;

Javascript object methods map() example

The map method creates a new array with the results of calling a provided function on every element in the calling or existing array. We have to supply an array, run that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case), and subsequently returns a new array once completed.

var numbers = [1, 4, 6, 10]; var doubles = numbers.map(function(x) < return x * 2; >); // doubles is now [2, 8, 12, 20] // numbers is still [1, 4, 6, 10] //ES6 example const numbers = [2, 14, 18, 22]; const halves = numbers.map(x => x / 2); // halves is now [1, 7, 9, 11] // numbers is still [2, 14, 18, 22] var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]

Javascript object methods filter() example

Javascript filter method to retrieve specific values from an array object if the condition is met.

const newArr = [ < id: 1, country: "England" >, < id: 2, country: "Scotland" >, < id: 3, country: "Wales" >, < id: 4, country: "Northern Ireland" >, < id: 5, country: "Republic of Ireland" >, < id: 6, country: "France" >, < id: 7, country: "Germany" >, < id: 8, country: "Italy" >, < id: 9, country: "Spain" >, < id: 10, country: "Belgium" >, < id: 11, country: "Holland" >, < id: 12, country: "Czech Republic" >]; const countries = newArr.filter((x) => < if(x.id % 4 === 0) < return x; >>); console.dir(countries); // Outputs following to web console [, , ]

Источник

What is an Array of Objects in JavaScript?

some more fun with Objects

An array in javascript is the collection of multiple types of data at a single place in order, and an array of objects in javascript is a collection of homogenous data, that stores a sequence of numbered objects at a single place.

Above, there is an array of objects myArr and we are accessing an object from the array by using array index myArr[1] , also printing the value on the console. As result, we are printing an object from an array of objects. This prints all the key-value pairs present at that particular index.

Читайте также:  Как вставить html тег

Syntax

Creating an Array of Objects

To create an array of objects in javascript, we have to declare an empty array first and then initialize it with the objects separated by a comma.

Above, we declared an array of objects where each array is separated by a comma and has three properties in each.

Array Properties

There are three types of properties in array Object: 1. Constructor — The constructor properties return a function that creates the Array prototype. This return function is a native code that is provided by the javascript engine.

Above, we have an array of objects myArr and we are printing its constructor properties on the console. As result, we print the function Array() < [native code] >on the console.

Here, we get the native code as a reference which is a predefined function inside the javascript engine responsible for creating the Array prototype.

2. Length — It returns the length of elements in an array i.e. the number of objects present in the array.

Above, we use the length properties on the myArr array of objects and also print it on the console. As result, we print 2 on the console.

3. Prototype — Array Prototype property helps to add new methods into the Array, for example- adding all values into an array. It also helps to add properties to the Array Object.

Above, we are adding a user-defined method into the Array Object. To do that, we accessed the Array prototype property using dot notation and added the user-defined function add into Array Object like this Array.prototype.add . Then, assigned an anonymous function to add , which is the definition of add method.

In the add method definition, we declare a result variable to store the array value count. Here, we are using the this keyword to reference the array on which the add method will get called and looping over the array. In each iteration, we are accessing the individual array values and adding them to the result variable, when all values inside the array get added to the result variable, we returned the final result .

Array Methods

Array methods are predefined methods into the Array Object prototype property. To use the array methods we call it on an array using object dot notation, using bracket notation will cause an error.

These are some frequently used array methods:

Array.push()

The push method helps to add a new value at the end of an array. To use it, we have to call the push method on an array by passing the value we want to add as a parameter. We can pass a single value as a parameter or multiple values separated by a comma.

Above, calling push method upon myArr array by passing a value 4 as a parameter also printing myArr on the console. As result, value 4 gets added at the end of myArr array, and [1,2,3,4] get printed on the console. The time complexity of the push method is O(1) and space complexity is O(N), where N is the length of the input.

Array.pop()

Array pop method helps to remove the last value from an array, it gives the removed value in return. To use it, we have to call pop() method on an array, which doesn’t take any parameter.

Читайте также:  Javascript toboolean abstract operation

Above, we have myArr array on which we are calling pop method. As result, the last value of the array myArr gets removed. Time complexity of the push method is O(1) and space complexity is O(1).

Array.shift()

Array shift method helps to remove the first value from an array, and in return, it gives the removed value. To use shift method, we have to call it on an array, and it doesn’t take any parameter.

Above, we have myArr array on which we are calling shift method. As result, the first value of the array myArr gets removed. Time complexity of push method is O(n) and space complexity is O(1).

Array.unshift()

Unshift method unshift to add a value at the beginning of an array. To use it, we have to call it on an array by passing the value we want to add as a parameter. We can pass a single value as a parameter or multiple values separated by a comma.

Above, calling unshift method on myArr array by passing a value 4 as a parameter. As result, value 4 gets added at the beginning of myArr array. Time complexity of push method is O(n) and space complexity is O(N), where N is the length of the input.

Array.slice()

Array slice method helps to copy an array without affecting the original array. To use it, we have called it on an array by passing the first and last index of the subarray we want to copy, but the value of the last index will not be included in the copied subarray. Leaving parameters blank will result in slice method default behavior, which will copy the whole array from index [0] to [n].

Above, we have myArr array on which we are calling slice method by passing first index 1 and last 3 as parameters. As result, we copy the subarray from index [1] to [3] which is [2,3]. Time complexity of slice method is O(n) and space complexity is O(N), where N is the length of the input. Time complexity of push method is O(n logn) and space complexity is O(N), where N is the length of the input.

Looping through an Array of Objects

We can loop through an array of objects using the for loop but available array methods make it much easier. So, we are going to use the map method to loop through an array of objects.

Above, we loop over an array of objects myArr using map method, in each iteration again looping over the individual objects and printing the properties key-value pair on the console. As result, we printed all the array object’s properties on the console.

Conclusion:

  • Array of objects in javascript is just an array having object data as its value.
  • Array methods are predefined methods that help to perform various operations on an array.
  • To make an array of objects in javascript, we have to declare an array and then add the object’s data as its value.

Источник

Оцените статью