Blog for Learning

This blog contains lesson material, material summary, questions and answers, definitions, types and examples, and others.


Powered by Blogger.


Flag Counter


Learning Javascript: Understanding Array Data Structures in Javascript

Javascript Tutorial: Learn about Array in Javascript
Imagine now that we are making a web application, then want to display a list of product names.
We can make it like this:
var produk1 = "Modem";
var produk2 = "Hardisk";
var produk3 = "Flashdisk";

Can it be like this?
It is allowed. But it is less effective.
What if there were 100 products, would we make 100 variables and do echo100x?
I'm tired.
Therefore, we must use Arrays.

What is an Array?

Before we discuss Array, we discuss first what is data structure?
Data structure is the methods or methods used to store data in computer memory.
One data structure that is often used in programming is Array .
An array is a data structure that is used to store a set of data in one place.
Each data in an array has an index, so we will easily process it.
The array index always starts from zero ( 0).
In the data structure theory ...
... The size of the array will depend on how much data is stored in it.

How to make an array in Javascript

In javascript, we can create arrays with square brackets ( [...]).
var products = [];
Then the variable productswill contain an empty array.
We can fill in the data into the array, then each data is separated by a comma ( ,).
var products = ["Flashdisk", "SDD", "Monitor"];
Anyway, because JavaScript is a dynamic typing programming language ...
... then we can store and mix anything in the array.
var myData = [12, 2.1, true, 'C', "Petanikode"];

How to retrieve data from an array

As we already know ...
The array will store a set of data and give it an index number to make it easily accessible.
The array index is always monitored from zero 0.
Suppose we have an array like this:
var makanan = ["Nasi Goreng", "Mie Ayam", "Mie Gelas"];
How do we take value "Mie Ayam"?
The answer is like this:
makanan[1] //-> "Mie Ayam"
Why not 2?
Remember: array indices always start from zero.
Let me be clearer, let's try it in the program:
<!DOCTYPE html>
<html lang="en">
    <title>Mengambil data dari array</title>
        // membuat array
        var products = ["Senter", "Radio", "Antena", "Obeng"];

        // mengambil radio
The result:
Retrieve data from an array

Print Array contents with Repetition

We can print all the contents of an array one by one like this:
What if later the contents of the array are there 100?
Of course we won't want to write 100 lines of code to print arrays.
The solution: Use looping .
Let's look at an example:
<!DOCTYPE html>
<html lang="en">
    <title>Array dan perulangan</title>
        // membuat array
        var products = ["Senter", "Radio", "Antena", "Obeng"];

        document.write("<h3>Daftar Produk:</h3>");
        // menggunakan perulangan untuk mencetak semua isi array
        for(let i = 0; i < products.length; i++){
            document.write(`<li>${ products[i] }</li>`);
The result:
Use looping to print all array contents
Pay attention ...
In the example above, we use properties lengthto take the length of the array.
We have 4data in the array products, then the property lengthwill be worth 4.
Then we use this property to limit the number of loops in for .
for(let i = 0; i < products.length; i++){
    document.write(`<li>${ products[i] }</li>`);
... and in block for, we print product contents with indices that refer to variables i.
Another way:
We can use looping method forEach().
<!DOCTYPE html>
<html lang="en">
    <title>Array dan perulangan</title>
        // membuat array
        var products = ["Senter", "Radio", "Antena", "Obeng"];

        document.write("<h3>Daftar Produk:</h3>");
        // menggunakan perulangan untuk mencetak semua isi array
        products.forEach((data) => {
The result will be the same as above.
Repeat an array with the forEach () method

How to Add Data to Arrays

There are two ways you can add data to an array:
  1. Fill in using indexes;
  2. Fill in using method push().
Fill in the index with this intention ...
Suppose we have an array with the contents as follows:
var buah = ["Apel", "Jeruk", "Manggis"];
There are three data in an array buah with an index:
  • 0"Apel"
  • 1"Jeruk"
  • 2"Manggis"
We want to add more data to the index 3, so we can do it like this:
buah[3] = "Semangka";
An array buahwill contain 4data.
Let's try the Javascript console .
Add data to the array
Right ...
"Semangka"we have added it to the array buah.
But the disadvantages of this method are:
We must know the amount of data or the length of the array, then we can add.
If we enter an arbitrary index number, then what will happen is that the data in the index will be overwritten.
Then what is the solution?
We use the method push().
We don't need to know how long the array is, because the method push()will add data to the array from the tail or back.
<!DOCTYPE html>
<html lang="en">
    <title>Mengisi data ke array</title>
        // membuat array
        var products = ["Senter", "Radio", "Antena", "Obeng"];

        // menambahkan tv ke dalam array products

        // menapilkan isi array
Then the result:
Break data with the push method
We can also add multiple data at once in this way:
products.push("Alarm", "Gemobok", "Paku");

How to delete array data

Just like adding data to an array, deleting data also has two ways:
  1. Use delete;
  2. Using method pop().
delete buah[2];
We can delete data with certain index numbers with deleteWhereas it pop()will remove from behind.
Short of delete, it will create empty space in the array.
Experiments in the console :
Delete data with delete
Of course this is not good ...
... because the array will still have length 4.
The second method uses the method pop(), the opposite of the method push().
The method pop()will delete the array at the back.
We can see the array in JavaScript as a stack , which has LILO (Last in Last out) properties .
Stack in Javascript
Let's try it in the console .
The pop function in javascript
We call the method pop()as many 4times, then the array will be empty []Because the contents are just 4that.
The method pop()will return the item value or data deleted from the array.

Deleting Data from Front

We can also delete data from the front using the method shift().
var bunga = ["Mawar", "Melati", "Anggrek", "Sakura"];

// hapus data dari depan
Then the deleted data is "Mawar".
Experiment on conosole:

Deleting Data on a Specific Index

If we want to delete data at certain inteks, then the function or method used is splice().
This function has two parameters that must be given:
array.splice(<indeks>, <total>);
  • <indeks> is the index of the data in the array to be deleted;
  • <total> is the amount of data to be deleted from that index.
Usually we give a total value with a value 1to only delete one data.
var bunga = ["Mawar", "Melati", "Anggrek", "Sakura"];

// hapus Anggrek
bunga.splice(2, 1);
Experiment on the console :
Delete data on a particular index
In the experiment above, if we do not fill in the <total>data to be deleted, then all data from the selected index will be deleted.

Change Array contents

To change the contents of an array, we can refill it like this:
var bahasa = ["Javascript", "Kotlin", "Java", "PHP", "Python"];
bahasa[1] = "C++";
Then it "Kotlin"will be replaced with "C++".
Experiment on the console :
Change data in array
It's easy not ...

Method-mothod Array

In addition to the methods or functions we have tried above, there are several methods in Array that we need to know.

1. Method filter()

The method filter()functions to filter data from arrays.
The parameters that must be given to the method are the filter()same as the method forEach(), namely: a callback function .
const angka = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Kita ambil data yang hanya habis dibagi dua saja
const filteredArray = angka.filter((item) => {return item % 2 === 0});

console.log(filteredArray) // -> [2, 4, 6, 8]
In the example above, we give arrow function as a callback function that will filter arrays.
Actually we can make it simpler like this:
const filteredArray = angka.filter(item => item % 2 === 0);

2. Method includes()

This method functions to check whether a data is in an array or not. Usually used to do a search to make sure the data is already in the array.
var tanaman = ["Padi", "Kacang", "Jagung", "Kedelai"];

// apakah kacang sudah ada di dalam array tanaman?
var adaKacang = tanaman.includes("Kacang");

console.log(adaKacang); // -> true

// apakah bayam ada?
var adaBayam = tanaman.includes("Bayam");

console.log(adaBayam); // -> false

3. Method sort()

The method sort()functions to sort data in an array.
var alfabet = ['a','f','z','e','r','g'];
var angka = [3,1,2,6,8,5];

console.log(alfabet.sort()); //->  ["a", "e", "f", "g", "r", "z"]
console.log(angka.sort()); // -> [1, 2, 3, 4, 5, 6, 7, 8, 9]

0 Komentar untuk "Learning Javascript: Understanding Array Data Structures in Javascript"

Silahkan berkomentar sesuai artikel

Template By Kunci Dunia
Back To Top