How is the Arrays in JavaScript?

How is the Arrays in JavaScript?

In JavaScript, array is a single variable that is used to store different elements

In JavaScriptarray is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. It’s a more convenient way to store and structure information than is defining of lots of variables with slightly different names, like this:

var fruit0 = 'Mango';
var fruit1 = 'Apple';
var fruit2 = 'Orange';

Instead of the above, we can use array to structure the data like this:

Var fruits = new Array('Mango','Apple','Orange');

Declaration of an Array

There are basically two ways to declare an array.

With the literal notation []

var array = [1, 2, 3]

With the Array() constructor

var array = new Array(1, 2, 3)

Basically both the approaches are same but most of the people use literal notation as it’s quicker to type and less code-intensive.

Arrays can be anything — numbers, strings, functions even other arrays and within the arrays you can mix different type of data freely.

var number = [1, 2, 3, 4, 5]
var strings = ['name', 'place', 'food' ]
var functions = [ function x(){...}, finction y(){...} ]
var mix = [ 12, 'niceplace', function xy(){...} ]

Accessing values of arrays.

We can access the values of an array by referring to an index number. Index number can be define as the location of an item in array. To get the value we refer to the members of an array using the index number in a square bracket [].

For example :

var array = [ 'val1', 'val2', 'val3']
alert(array[0]); // alerts val1.

note : indexing of arrays starts from 0 in the above example you can see array[0] alerts the first value of the array while array[1] will alert the 2nd value. To check this you can define an array and use console.table to see the indexing of the array.

Creating an Array of Arrays

An array of arrays is known as multi-dimensional array or matrix. These are constructed like this :

var Avengers = [
    [ 'ironman', 'dr.strange', 'cap.america' ],
    [ 'blackwidow', 'scarletwitch', 'wasp' ]
];

You can also construct a multi-dimensional array using Array() constructor like this :

var Avengers = new Array(
   new Array('ironman', 'dr.strange', 'cap.america'),
   new Array('blackwidow', 'scarletwitch', 'wasp')
);

Items in a multi-dimensional array are addressed in the same way as single arrays, but for the difference we address each item using multiple values, starting from the outermost array. For example, the value of wasp is located at index of 1 of the outermost array, and index 2 of the nested array, so we would refer to it as Avengers[1][2].

For better understanding consider this table :

Indexing an Array with Strings Instead of Numbers

We can index an array using strings, instead of numbers. This is often useful when we use multi-dimensional arrays to group related data.

We can’ t directly put together an array with string indexes and populate it, for this we have to first create an empty array and then index and populate it.

var Avengers = [];
Avengers['males'] = [ 'ironman', 'dr.strange', 'cap.america' ];
Avengers['females'] = [ 'blackwidow', 'scarletwitch', 'wasp' ];

Now, we can reference ‘ironman’ as Avengers[‘males’][0], and ‘scarletwitch’ as Avengers[‘females’][1].

Turning an Array into a String.

JavaScript provides a number of methods for processing arrays. One of the most useful is the ability to turn an array into a string.

By join() method

The join method concatenates all the members of an array into a string, along with a separator. If the separator argument is omitted, a comma is used by default:

var Avengers = [ 'ironman', 'dr.strange', 'cap.america' ];
var together = Avengers.join('');
alert(together); 
var list = Avengers.join();
alert(list);
var sentence = Avengers.join(' and ')
alert(sentence);

Now, together is ‘ironmandr.strangecap.america’, list is ‘ironman,dr.strange,cap.america’ and sentence is ‘ironman and dr.strange and cap.america’.

By toString() method

You can also convert the Array into a string by the toString() method.

var Avengers = [ 'ironman', 'dr.strange', 'cap.america' ];
var together = Avengers.toString();
alert(together); // ironman,dr.strange,cap.america

toString method also works the same way as the join() method do but unlike join() which can join an array together by a separator, toString() method join an array by comma separated only.

Adding or Removing Members from an Array

To modify or delete data from an array you must know how to add or remove members from an array. JavaScript provides various methods to add, remove or change data of an array. Some of the methods do the same task but have different approach.

Changing/Replacing an existing value with a new one.

So now, you created an array and for some reason you want change a specific value of an array. This can be done by the assignment operator.

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[0] = 'Mocha';
alert(Coffee);

Now, Coffee is Mocha,Cappuccino,Expresso,Latte.

Well this method can be useful to change a specific value but let say you by mistake give reference to an index number which doesn’t have any value contain any value. In that case JavaScript just adds the value you assigned to that index. For example

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[4] = "Macchiato";
alert(Coffee);

Macchiato will be added to the array at index 4.

Now Cofffee is Mocha,Cappuccino,Expresso,Latte,Macchiato

But this way of adding items in an array is not a good practice. Consider the given example

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[5] = "Macchiato";
alert(Coffee);

In this you can see we have 4 item in the array and the last index is 3. Instead of referring 4th index to assign the value, we referred to the 5th one. This will create an empty or null value between the 3rd and 5th index.

empty value at index 4.

So to add or remove values without any issue, JavaScript provide various method to work upon and ease our work.

Adding Members : The push() and unshift() method

The unshift() method adds new items to the beginning of an array, and returns the new length.

var DBZ = ['Goku', 'Vegita', 'Gohan', 'Goten'];
DBZ.unshift("Frieza");
alert(DBZ);

DBZ will now be Frieza,Goku,Vegita,Gohan,Goten.

The push() method appends the given element(s) in the last of the array and returns the length of the new array.

var DBZ = ['Goku', 'Vegita', 'Gohan', 'Goten'];
DBZ.push("Trunks");
alert(dbz);

DBZ will now be Goku,Vegita,Gohan,Goten,Trunks

Removing Members : The pop() and shift() method

Like push() and unshift() JavaScript provides two useful methods to remove an item from the beginning and the end.

The shift() method removes a first item from an array and returns that removed element. This method changes the length of the array on which we are calling the shift() method.

var Naruto = ['Naruto', 'Sasuke', 'Sakura', ' Hinata'];
Naruto.shift();
alert(Naruto);

Now Naruto will be Sasuke,Sakura, Hinata

The pop() method removes a last element of an array and returns that element.

var Naruto = ['Naruto', 'Sasuke', 'Sakura', ' Hinata'];
Naruto.pop();
alert(Naruto);

Now Naruto will be Naruto,Sasuke,Sakura

Understanding splice() and slice() methods

Now we know how to add/remove an item from an array from the beginning or end. It’s time to understand how you can add or remove item from between the elements of an array.


The 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.

Syntax:

Array.splice( index, remove_count, item_list )

. index : Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

. remove_count : Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

. item_list : Optional. The new item(s) to be added to the array.

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2); // remove ["Charmander", "Squirtle", "Caterpie"]
alert(Pokemon); // Pikachu,Bulbasaur

Let’s remove ‘.Charmander’ from the list.

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2,1);
alert(Pokemon); // Pikachu,Bulbasaur,Squirtle,Caterpie

Let’s add ‘Evolve’ between ‘Bulbasaur’ and ‘Charmander’

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2,0,'Evolve');
alert(Pokemon);  
// Pikachu,Bulbasaur,Evolve,Charmander,Squirtle,Caterpie

The slice() method returns the selected elements in an array, as a new arrayobject. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

Syntax :

Array.slice(start, end)

. start : An integer that specifies where to start the selection. Use negative numbers to select from the end of an array.

. end : An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

var life = ['eat', 'sleep', 'code', 'repeat'];
var slice = life.slice(2);
alert(slice); // code,repeat
alert(life) // eat,sleep,code,repeat 

Original array will remain intact.

Now let’s remove ‘eat’ and ‘repeat’ item from the array.

var life = ['eat', 'sleep', 'code', 'repeat'];
var slice = life.slice(1,3);
alert(slice) // sleep,code

You can also check whether the item you selected is present in the array or not by includes() method which will give either true or false depending upon the item present or not in the list respectively.

checking presence of item in an array by includes() method

Sorting an Array into Alphabetical or Numerical Order

Sorting by letter or number allows you to order data by particular criteria. You could order names alphabetically, or phone numbers by area code etc.

The sort() method will sort an array into alphabetical order.

var songs = [’Voices’, ’Wasteland’, ’Gravity’, 'Scream’, 'Runaway’];
songs.sort();
alert(songs);

Now the sorted array will be Gravity,Runaway,Scream,Voices,Wasteland

To sort numeric values, we can’t use sort() method directly. For numeric sort we have to write an additional function :

var score = [25, 8, 5, 2, 4, 1, 7, 1995];
score.sort(function(a,b){
return a-b } 
);

Sorted array will now be 1, 2, 4, 5, 7, 8, 25, 1995.

Reversing an Array

JavaScript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first.

Syntax :

Array.reverse();

Examples :

var Avengers = [
    [ 'ironman', 'dr.strange', 'cap.america' ],
    [ 'blackwidow', 'scarletwitch', 'wasp' ]
];
Avengers.reverse();
alert(Avengers); 
// blackwidow,scarletwitch,wasp,ironman,dr.strange,cap.america

See here not only the inner elements but the outer elemens are also reversed.

For better understanding consider this table :

original Array

Array after reversing.

Thanks for reading!

Java vs JavaScript: Difference between Java and JavaScript

Java vs JavaScript: Difference between Java and JavaScript

The video on Java vs JavaScript provides you with a short and crisp description of the two programming languages. You will also see the head to head comparison between the two on various aspects and learn the similarities and differences between them.

Java vs JavaScript: Difference between Java and JavaScript 

The video on Java vs JavaScript provides you with a short and crisp description of the two programming languages. You will also see the head to head comparison between the two on various aspects and learn the similarities and differences between them.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

Top 4 Spring Annotations for Java Developer in 2019

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

JavaScript != Java

Lately I've been doing a lot of work with Java and JavaScript through JavaScript Engine and every time I come to a question about the two someone feels the need to answer the question with,&nbsp;<em>"Java and JavaScript are two different languages. They have nothing in common!"</em>&nbsp;or&nbsp;<em>"Just because the word Java is in JavaScript doesn't mean its Java"</em>&nbsp;or&nbsp;<em>"Java != JavaScript"</em>.

Lately I've been doing a lot of work with Java and JavaScript through JavaScript Engine and every time I come to a question about the two someone feels the need to answer the question with, "Java and JavaScript are two different languages. They have nothing in common!" or "Just because the word Java is in JavaScript doesn't mean its Java" or "Java != JavaScript".

Well OK... That doesn't answer the question and it is so irrelevant because you can obviously use Java inside of JavaScript and you can use JavaScript inside of Java so just because someone is asking a question about the two doesn't mean they think they're are the same language.

So my question is how come so many people seem to get worked up over the fact someone is trying to use Java and JavaScript together and will dismiss the question with their condescending phrases instead of offering a solution?

Here is an example,

var SwingGui = JavaImporter(Packages.javax.swing,
                    Packages.javax.swing.event,
                    Packages.javax.swing.border,
                    java.awt.event,
                    java.awt.Point,
                    java.awt.Rectangle,
                    java.awt.Dimension);
...

with (SwingGui) {
var mybutton = new JButton(test);
var mypoint = new Point(10, 10);
var myframe = new JFrame();
...
}

sources:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java

http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/

http://www.oracle.com/technetwork/articles/javase/scripting-140262.html

How to Use TensorFlow Using Java/JavaScript

How to Use TensorFlow Using Java/JavaScript

This article will help get experienced Java/JavaScript developers use machine learning/deep learning in the TensorFlow ecosystem without any prior knowledge of Python.

Background

Nowadays, there is a great market for machine learning and deep learning enthusiasts, as it is a niche technology, but it also requires different programming skillset.

There are plenty of tools and libraries available for this like Numpy, Keras, and TensorFlow, but most of them play around R, MATLAB, and, of course, Python.

So, now the problem is reskilling the existing programmer community, which is typically trained on languages like C, C++, and Java.


You might also enjoy: Machine Learning In Node.js With TensorFlow.js


Solution

There is lots of misconception that TensorFlow is made only for Python and its allies. Don't worry, if you are an experienced Java/JS programmer and want to get your hands dirty with ML/DL, you still can!

The solution is TensorFlow for Java and TensorFlow.js.

Learn by Example

Java

To start with Java, you need to first to set up a Maven project and add the following dependency to your pom.xml.

<dependency>
	<groupId>org.tensorflow</groupId>
	<artifactId>tensorflow</artifactId>
	<version>1.7.0</version>
</dependency>

This is an enumeration of two libraries:

  • libtensorflow
  • libtensorflow_jni

This wraps the TensorFlow C++ library and JNI connector to access it through Java programs.

Additionally, you can add the following dependency to support GPU acceleration. By default, it works on CPU powers.

<dependency>
	<groupId>org.tensorflow</groupId>
	<artifactId>libtensorflow_jni_gpu</artifactId>
	<version>1.7.0</version>
</dependency>

Now, you are all set to use TensorFlow features on Java. You can use following test program to check the environment.

import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

public class HelloTF {
  public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
      final String value = "Hello from " + TensorFlow.version();

      // Construct the computation graph with a single operation, a constant
      // named "MyConst" with a value "value".
      try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
        // The Java API doesn't yet include convenience functions for adding operations.
        g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      // Execute the "MyConst" operation in a Session.
      try (Session s = new Session(g);
           Tensor output = s.runner().fetch("MyConst").run().get(0)) {
        System.out.println(new String(output.bytesValue(), "UTF-8"));
      }
    }
  }
}

This is basically creating an operation graph with a const and assigning a value as the current version. For fetching it, you need to run it inside a session.

JavaScript

To start with JavaScript, you just need a single package available through CDN. It's available through an NPN package, as well, but it is easier to use CDN for working with a browser.

Add the below script tag to your HTML file.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>

That's it. Now, you can test TensorFlow features like training, re-training, and converting existing models into JavaScript-compatible models right into your browser.

To test, you can use following code.

// Define a model for linear regression.
    const model = tf.sequential();
    model.add(tf.layers.dense({units: 1, inputShape: [1]}));

    // Prepare the model for training: Specify the loss and the optimizer.
    model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

    // Generate some synthetic data for training.
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

    // Train the model using the data.
    model.fit(xs, ys).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        result = model.predict(tf.tensor2d([5], [1, 1]));
    });

This is a basic linear regression model trained with mean square error and gradient descent.

You can have a look at a complete example on GitHub.

Originally published by Vinod Pahuja at dzone.com