Tag Archive for: Array



There are multiple ways of writing a program that selects a random element from an Array, but the best-suited method is to use a combination of Math.random() and Math.floor() methods. Math.random() method provides the user with a random floating-point value between 0 and 1. While the Math.floor() method simply takes in a floating-point value and rounds down the value to make it an integer.

Method 1: Random element from an Array Using Math.random() & Math.floor()

First, create an array with the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

This array represents a list of cities to choose from at random. After this, simply create a new function that takes in the array as a parameter like:

function elemenet_Selector(arr) {
 
}

Within this function, the very first thing is to get the length of the array passed to it inside a separate variable:

array_length = arr.length;

Then, simply call the Math.random() method to get a floating-point value and then multiply that number with the length of the array to get the range between 0 and array length:

value = Math.random() * array_length;

This line will return floating point values, but they are no good when it comes to being the index of an array. Confirm this by simply wrapping this line into the console log and observing the output:

The output on the terminal is as:

To change these values into an integer, simply pass the value variable into the Math.floor() method and remove the console.log(value) line:

indexValue = Math.floor(value)

At the end of the function, use a return statement and return the element at the indexValue of the array:

After that, come out of the function element_Selector, and make a call to this function and wrap that call inside a console log function to print out the randomly selected element:

console.log(elemenet_Selector(my_arr));

The complete code snippet is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

function elemenet_Selector(arr) {
  array_length = arr.length;
  value = Math.random() * array_length;
  indexValue = Math.floor(value);
  return arr[indexValue];
}

console.log(elemenet_Selector(my_arr));

Execute this program and observe the following result:

It is clear from the output that random elements are selected from the array.

Method 2: Using Double NOT Bitwise Operator

Start by creating an array just like in method 1 with the help of the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

Afterwards, call Math.random() and multiple it with the length of our array to get a range from 0 to the length:

value = Math.random() * my_arr.length;

This time around, to convert this value into an integer representing the index of the array, simply apply the double NOT Bitwise operator, which is the double tilde operator (~~), and fetch the value from the array as:

var item = my_arr[~~value];

Last, simply print out the randomly selected element onto the terminal with the help of console log function:

Complete code snippet for method 2 is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];
value = Math.random() * my_arr.length;
var item = my_arr[~~value];
console.log(item);

Execute this program and observe the following result:

It is clear from the output that a random element is being selected from the array

Conclusion

In JavaScript, we can utilize the Math.random() function with either the Math.floor() function or the double NOT Bitwise operator to fetch a random item from an array. Math.random(), when multiplied by the length of the array, provides a range value of index between zero and the array’s length. However, this range value is in floating point, therefore, use Math.floor() or NOT Bitwise operators to convert it into an integer to be used as the array index. This article has explained both of these methods along with an example



Source link


The Array.isArray() was released with the release of ECMAScript5 JavaScript. This method simply checks whether the argument passed to its arguments is an array or not. This article will explain this Array isArray() method by explaining its syntax and then showcasing some examples.

We will start by going over the syntax of the Array isArray() method.

Syntax
Observe the syntax of the Array isArray() below:

In this syntax:

  • Array is the default JavaScript Array Object
  • Object is the argument, the one we want to determine as an array or not

Return Type

  • Boolean: Returns true if the object passed to this method was actually an array otherwise it would return false

Additional Information

Since this is a method of the default JavaScript Array Object, therefore it is also known as the static property of this Array Object.

Example 1: Passing an Array to Array.isArray() Method

To demonstrate the working of this method, first create an array of the same types of values with the help of the following line:

my_object = [1, 2, 3, 4, 5, 6, 7, 8, 9];

After that, pass this array to the Array.isArray() method and store the return value in a new variable named as the result:

result = Array.isArray(my_object);

After that, simply display the value inside the result variable on the terminal using the console log function:

Execute the code, and observe the output to be:

The output shows that the object passed to this method was actually an array.

Example 2: Passing an Array With Different Data Type Values

To check whether this method works with an array containing values of different data types, create an array using the following line:

my_object = [1, 2, «Google», 4, true, 6, «7», 8.673, 9];

Pass this object into the Array.isArray() method and store the result in a result variable:

result = Array.isArray(my_object);

Afterwards, simply print the result from the result variable onto the terminal using the console log() function:

Execute the code and observe the following output:

From the output, it is conclusive that the type of data stored inside the array doesn’t matter. It only checks whether the object is an array or not, which in this case was true.

Example 3: Passing a String Object in Array.isArray() Method

To demonstrate what happens when a non-array object is passed to the Array isArray() method, create a new string variable with the help of the following line:

string_var = «Hello World»;

Pass this string value into the arguments of the Array.isArray() method and store the outcome in a new variable:

result_var = Array.isArray(string_var);

Print the value inside the result_var on the terminal using the console log() function:

Execute the program and get the following output on the terminal:

It returns that the object passed into its argument was not an array.

Conclusion

The Array.isArray() method is pretty simple. It simply checks whether the object in its argument is an array or not and returns true or false to the caller. If an array is being passed, the values or even the data types of its values don’t matter. In this article, we have learned about the different outcomes of the Array.isArray() method with the help of different examples.



Source link


“The array variable is used in any programming language to store multiple data. The PERL array can contain different types of data such as numbers, strings, Boolean, etc. The “@” symbol is used to declare an array in PERL, and the “$” symbol is used to read the value of the particular array index. The command-line argument values are stored in the PERL array named @ARGV. The uses of the PERL array of the numeric index have been shown in this tutorial.”

Create Array

Different ways to create the PERL array have been shown in this part of this tutorial.

A. Create an Array by Initializing Values

The “@” symbol is used to declare a PERL array with values. The array values are separated by a comma with the first brackets in this type of declaration. Different arrays have been created by initializing the values in the following example.

Example

Create a PERL file with the following code that shows the way of declaring different types of arrays in PERL. Here, the first array contains 4 string values, the second array contains 6 number values, and the third array contains 3 strings and 3 number values. The values of three arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,).

#Define first array
@strArray = («book»,«Pen», «Pencil», «Ruler»);
#Define second array
@numArray = (45, 67, 23.89, 12.43, 23, 78);
#Define third array
@mixArray = («book», 45, «Pen», 10, «Pencil», 5);
#Print array values
print «Array1:», join(‘,’, @strArray),«n«, «Array2:», join(‘,’,@numArray),«n«,«Array3:», join(‘,’,@mixArray),«n«;

Output
The following output will appear after executing the above code.

B. Create an Array by Using the “qw” Operator

The “qw” operator is used to create a PERL array from a string value based on the white space. The “@” symbol is used to declare a PERL array like before. Different arrays have been created by using the “qw” operator in the following example.

Example

Create a PERL file with the following code that shows the way of declaring different types of arrays in PERL by using the “qw” operator. Here, the first array contains 4 string values, the second array contains 6 number values, and the third array contains 3 strings and 3 number values. The values of three arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Define first array
@strArray = qwRose Lily Daisy Zinnia;
#Define second array
@numArray = qw5 6 2.89 1.43 3 8;
#Define third array
@mixArray = qwRose 45 Dalia 10 Lily 5;
#Print array values
print «Array1:», join(‘,’, @strArray),«n«, «Array2:», join(‘,’,@numArray),«n«,«Array3:», join(‘,’,@mixArray),«n«;

Output
The following output will appear after executing the above code.

C. Create an Array by Initializing Each Value Separately

Each value of the array can be initialized separately by mentioning the index value or adding a value without whitespace using the “qw” operator. The “$” symbol is used to set each value of the array. Different ways to create an array by adding a single value have been shown in the following example.

Example

Create a PERL file with the following code that shows the way of declaring the value of an array by mentioning the index value. Here, four string values are added by using double quotes, and 2 string values are added by using the “qw” operator. The values of the array have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Define array values using index and ‘qw’ operator
$months[0] = «January»;
$months[1] = «February»;
$months[2] = qw/March/;
$months[3] = qw/April/;
$months[4] = «May»;
$months[5] = «June»;
#Print the array values
print «Array values:n«, join(‘,’, @months),«n«

Output
The following output will appear after executing the above code.

D. Create Sequential Array

The array of sequential values can be created by using the range values. The “@” symbol is used to declare the range array. Different types of range arrays have been mentioned in the following example.

Example

The sequential array values can be initialized by defining the range. Create a PERL file with the following code that will show the way of initializing array values by using numeric range and character range. The values of these arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Declare array of sequantial numbers
@numArray = (10..20);
#Declare array of sequantial characters
@charArray = (A..M);
#Print the array values
print «Number Array:», join(‘,’, @numArray),«n«, «Character Array:», join(‘,’,@charArray),«n«

Output
The following output will appear after executing the above code.

Access Array Values

All array values can be accessed by using the loop, and the particular array value can be accessed by mentioning the index value. The “$” symbol is used to print a particular array value. The following example shows different ways to access array values.

Example

Create a PERL file with the following code that shows the way of accessing array values in different ways. An array of string values has been defined in the code. Next, the 2nd and 3rd elements of the array have been accessed by mentioning the index value. The foreach loop has been used to access all values of the array and print each value in each line.

#Define the first array
@strArray = («book»,«Pen», «Pencil», «Ruler»);
#Print individual value
print «The value of 2nd index: «,$strArray[1],«nThe value of the 3rd index: «, $strArray[2],«n«;
#Print all array values
print «Array values are:n«;
foreach $value (@strArray)
{
    print «$valuen«;
}

Output
The following output will appear after executing the above code.

Conclusion

The way of creating and accessing the PERL array has been shown in this tutorial by using multiple PERL examples. I hope this tutorial will help the PERL users to know the purpose of using the PERL array properly.



Source link


“The length of an array indicates the number of elements of the particular array. Many ways exist in PERL to calculate the array length. When the length of the array is calculated by using the “@” symbol, then it is called an implicit scalar conversion. When the length of the array is calculated by using the scalar keyword, then it is called an explicit scalar conversion. The “#” symbol can also be used to count the length of the array. Different ways of counting the array length and using it in the PERL scripts have been shown in this tutorial.

Different ways of counting the array length have been described in the next part of this tutorial by using examples.”

Example-1: Count the Array Length Using the “@” Symbol

Create a PERL file with the following code that will count the length of an array by using the “@” symbol. An array of 5 string values has been defined in the code. The total number of array values has been stored into a variable named $length that has been printed later.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Count the array length
$length = @myArr;
# Display the array length
print «The array contains $length elements.n«;

Output

The following output will appear after executing the above code.

Example-2: Count the Array Length Using the Scalar Keyword

Create a PERL file with the following code that will count the length of an array by using the scalar keyword. An array of 6 numbers have been defined in the code. The scalar keyword has been used to count the total number of elements of the array. Next, two values were added to the array and again counted, the total number of elements of the array. The join() function has been used to print the array values with the space.

# Define an array of numbers
@numbers = (6, 5, 3, 1, 2, 8);
# Print the array values
print «Array values are:n«, join(‘ ‘,@numbers), «n«;
# Print the total number of elements of the array
print «Total elements of the array is «, scalar @numbers, «n«;
#Add two new elements
$numbers[@numbers] = 9;
$numbers[@numbers] = 4;
# Print the array values after adding two values into the array
print «Array values after adding two elements are:n«,join(‘ ‘,@numbers), «n«;
# Print the length of the array after insertion
print «Total elements of the array is «, scalar @numbers, «n«;

Output

The following output will appear after executing the above code. The total number of elements of the array after adding two elements is 6+2 = 8.

Example-3: Count the Array Length Using the “#” Symbol

Another way of counting the total number of elements of the array is using the “#” symbol. The last index of the array is counted by using the “#” symbol. So the total array elements can be counted by adding 1 with the last index value. Create a PERL file with the following code that will count the array length by using the “#” symbol. An array of 5 float numbers has been defined in the code. The pop() function has been used to remove 3 elements from the array. The join() function has been used to print the array values with the space.

# Declare an array of float numbers
@float_num = (45.89, 34.12, 56.34, 90.34, 45.23);
# Print the array values
print «Array values:n«, join(‘ ‘,@float_num), «n«;
# Print the length of the array
print «Total number of array elements : «, $#float_num+1, «n«;
# Remove three elements from the array
pop @float_num;
pop @float_num;
pop @float_num;
# Print the array values
print «Array values after removing three elements:n«, join(‘ ‘,@float_num), «n«;
# Print the length of the array after removing three values
print «Total number of array elements after removing the elements: «, $#float_num+1, «n«;

Output

The following output will appear after executing the above code. The total number of elements of the array after removing 3 elements is 5-3 = 2.

Example-4: Print the Array Values Using Array Length

Create a PERL file with the following code that will use the length of the array to iterate the values of the array using for loop and print the array values in each line. The last index value of the array has been used here to count the length of the array.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Iterate the array values based on the array length
for($i = 0; $i < $#myArr+1; $i++)
{
# Print the array values
print $myArr[$i], «n«;
}

Output

The following output will appear after executing the above code.

Example-5: Count the Array Length Using Loop

Another simple way to count the array length is by using any loop. Create a PERL file with the following code that will count the array length by using the foreach loop. An array of 5 string values has been defined here. A counter variable has been used in the code to count the length of the array by incrementing the counter value by 1 in each iteration of the loop.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Initialize the counter
$counter = 0;
print «Array values:n«;
# Iterate the array values based on the array length
foreach $val (@myArr)
{
# Print the array values
print $val, «n«;
$counter++;
}

# Print the length of the array
print «nTotal number of array elements : «, $counter, «n«;

Output

The following output will appear after executing the above code.

Conclusion

The way of counting the array values in PERL has been shown in this tutorial by using multiple examples. The PERL user can use any of the ways to find out the array length and use it for solving PERL programming problems.



Source link


As we know that arrays are very important for a programming language as they group the values of same data type in one variable so in Java array also play a positivo role. When we create functions or methods we usually pass variables as arguments. But what if we want to return a large amount of data having same data type at merienda from a function or method?

We can do that by returning an array where we want to use numerous values of the same data type without occupying the large memory space.

How do we return an array in Java?

In Java, we can return an array from a function. The following practical example, will showcase how to return an array practically in Java.

Code:

public class arry {
    public static int[] rtnarray() {
        int[] ary = {0,2,4,6,8,10,12,14,16,18,20};
        return ary;
    }
    public static void main(String[] args) {
        int[] get = rtnarray();
        int q = 0;
        while(q<get.length)
        {
            System.out.println(«The value at index-number « + q + » is: « +get[q]);
            q++;
        }
}
}

In this code, we create a static function which will return an integer type array. Then in the main function, we create an integer type array variable and initialize it with the function that returns an integer array. Lastly, we use a while loop to display the elements of the array.

Output:

The output clearly shows that we can return an array with the help of a method and display the required result.

Here you go! You have learned to return an array in Java.

Conclusion

In java, an array can be returned with the help of a method or a function. For this purpose, the method return type must be the type of the array, and the variable that stores the array also has the same data type as the array. In this article, we talked about we have gone through the prose in detail through which we can return an array in Java.



Source link


In Java, arrays can be single-dimensional, 2-dimensional, or multi-dimensional. Java’s two-dimensional arrays are arrays within some other arrays. The 2D arrays are also known as matrices and they keep the data in the form of a table i.e. columns and rows. A 2D array can be created by specifying a data type followed by an array name and two sets of square brackets. In java, there are multiple ways to print a 2D array such as using for-each loop, for-loop, etc.

In this write-up, we will explain how to use the below-listed approaches to print a 2d array in Java:

So, let’s get started!

How to use nested for-loop to print a 2d array in Java?

The below-given example will guide you how to use nested for-loop to print a 2D array in java:

public class ExampleClass {
    public static void printArray(String array[][]) {

        for (int row = 0; row < array.length; row++)
        {
            for (int ind = 0; ind < array[row].length; ind++) {
                System.out.print(array[row][ind] + » «);
            }
            System.out.println();
        }
    }

    public static void main(String args[]) throws IOException {
        String originalArray[][] = {
            {«John», «Joe», «Mike»},
            {«Shaun», «Alex», «Henry»},
            {«Williams», «Dean», «Seth», «Ambrose»}};
        printArray(originalArray);
    }
}

Firstly, we created a printArray() method that takes a 2D array as an argument. Within the printArray() method, we utilized the nested for-loop to traverse through all the elements of the given array.

In the main method, firstly, we created a 2D string-type array and afterward we invoked the printArray() method:

The output verified that the nested for-loop successfully printed all the elements of the 2dimensional array.

How to use the for-each loop to print a 2-dimensional array?

Another way to print a 2-dimensional array is use of for-each loop. Let’s consider the following code block to learn how to print a 2D array in Java:

public class ExampleClass {
    public static void printArray(String array[][]) {
        for (String[] traverseRow : array) {
            for (String ind : traverseRow) {
                System.out.print(ind + «,»);
            }
            System.out.println();
        }
    }
    public static void main(String args[]) throws IOException {
        String originalArray[][] = {
            {«John», «Joe», «Mike», «Ambrose»},
            {«Shaun», «Alex», «Henry»},
            {«Williams», «Dean», «Seth»}};
        printArray(originalArray);
    }
}

This example remained the same as the previous one. The only difference is that, this time we utilized the foreach loop instead of for-loop:

This is how we can utilize the for-each loop to print a 2-dimensional array in java.

How to use Arrays.deepToString() to print a 2-dimensional array in Java?

A 2-dimensional array can be converted into a string using Java’s Arrays.deepToString() method. In the below-given code block, we’ll demonstrate how to print a 2-dimensional array in Java using the Arrays.ToString() method:

int[][] originalArray = {{12, 17, 18, 27}, {19, 44, 13, 18}};
System.out.println(Arrays.deepToString(originalArray));

In this coding example, initially, we created an integer-type 2-dimensional array. After that, we printed the 2D array using the “Arrays.deepToString()” method. The detailed code and output will be shown in the following snippet:

The above snippet shows that “Arrays.deepToString()” successfully printed the elements of the 2d array.

Conclusion

Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays.deepToString() method, etc. Each approach follows a different procedure, but all of them can still accomplish the same goal, i.e., printing a 2D array. A couple of suitable examples were provided in this post to illustrate how to print a 2d array in Java using various techniques.



Source link


JavaScript allows us to perform different functionalities on the arrays for example splitting the arrays into subarrays, concatenating multiple arrays, removing array elements, and so on. Splitting/converting a string into an array of characters is very common in JavaScript. Therefore, JavaScript offers multiple methods to get a character array from a string such as array.split() function, array.from() function, spread operator, and so on.

This post will present a comprehensive overview of the below-listed methods to get a character array from a string in JavaScript:

So, let’s begin!

string.split() function in JavaScript

split() is a built-in function in JavaScript that splits/breaks a string into substrings(words or characters). It produces a new modified array without affecting the given array.

Syntax
The below snippet will assist you to understand the syntax of the array.split() method:

string.split(separator, limit);

Both separator and limit are optional parameters. A string/regular expression can be passed as a separator to the split() method. If we didn’t specify any parameter then the split() method will return the innovador string.

Example: Get a character array using the split() method
In this example program, we will understand how to use the split() method to get an array of characters from the given string:

var originalString = «Welcome to linuxhint»;
var resultantArray = originalString.split(«»);
console.log(«Resultant Array: «, resultantArray);

In this program, we passed “” as a separator to the split method. Consequently, the split() method will break the given string into characters and it will return an array of characters as shown in the below-given snippet:

This is how we can get a character array from a string in JavaScript using the split method.

substring() function in JavaScript

The substring() method in JavaScript is used to extract a certain number of characters/letters from the given string. The substring() function extracts the characters between two positions and returns a new modified array without affecting the innovador array.

Syntax
The below snippet will explain the basic syntax of the substring() method:

substring(initial_index, final_index);

Here, the initial_index is a required parameter that specifies the starting position while the final_index is an optional parameter that specifies the end position. Omitting the second parameter, i.e. final_index will return the rest of the string.

Example: Get a character array using the substring() method
In this program, we will learn how to use the substring() function to get an array of characters from the given string:

var originalString = «linuxhint»;
var newArray = [];
for (i = 0; i < originalString.length; i++) {
newArray[i] = originalString.substring(i, i + 1);
}
console.log(«Resultant Array: «, newArray);

In this program, we utilized the substring() method to get the characters from the given string and store them in an array:

In this way, we can utilize the substring() method to get the array from the given string in JavaScript.

substring() function in JavaScript

It is a built-in static method in JavaScript that returns a new array from any iterable object. In simple words, the from() method enables us to create a new array from iterable objects or array-like objects.

Syntax
The basic syntax of the from() method will be something like this:

array.from(object, mapFun, thisArg);

Here, the object parameter represents an object to be converted to an array. The mapFun parameter represents a call-back function that will be invoked on each element while thisArg is a value that is used as this value for the map function. The object is a compulsory parameter while mapFun and thisArg are optional parameters.

Example: Get a character array using the from() method
In this program, we will learn how to use the substring() function to get an array of characters from the given string:

var originalString = «Welcome»;
var newArray = Array.from(originalString);
console.log(«Resultant Array: «, newArray);

In this example, we passed the “originalString” to the “Array.from()” method to get a character array from the given string:

This is how the Array.from() method works in JavaScript.

Conclusion

In JavaScript, different methods such as Array.from(), string.substring(), string.split() etc. are used to get an array of characters from the given string. The split() method splits the given string into substrings, the substring() function extracts a specific number of characters from the given string, and from() method returns a new array from any iterable object. This post explained different methods to get an array of characters from the given string in JavaScript.



Source link


In JavaScript, we can perform various tasks on arrays such as popping/pushing array elements, removing duplicate elements, concatenating array elements, and so on. Removing duplicate elements from an array is a very simple but very crucial task in the programmer’s life. Therefore, JavaScript offers numerous approaches for removing duplicate elements from an array such as the use of JavaScript Set, indexOf() method, filter() method, and so on.

This post will explain the below-given methods to delete the duplicate array elements in JavaScript:

So, without a further delay, let’s get started!

How to use Set in JavaScript to remove duplicate array elements?

A Set in JavaScript allows us to store the unique elements of any data type such as primitive, or object references. This means each value will occur only merienda in a collection.

Example: Remove Duplicate elements using Set

Let’s consider the below code snippet where we have an array named “languages” that consists of some duplicate elements. The task is to remove those duplicate elements using JavaScript Set:

1
2
3
4

var languages = [«Java», «JavaScript», «Java», «C++», «C», «Java», «C++», «JavaScript», «C++», «Java»];
console.log(«Llamativo Array: «, languages);
var uniqueLanguages = [new Set(languages)];
console.log(«Filtered Array: «, uniqueLanguages);

In this program, we performed the following functionalities:

  • Created an array that contains duplicate elements.
  • Utilized console.log() method to print innovador array elements.
  • Created a Set using the new Set() method named “uniqueLanguages”, and passed it an array i.e. “languages”.
  • Consequently, the “uniqueLanguages” Set removed the duplicated languages and returned only unique elements:

In this way, we can utilize the JavaScript Set to remove duplicate elements from an array.

How to remove duplicate array elements using indexOf() method?

It is a predefined function in JavaScript that is used to get first occurrence of an array element. It is a case-sensitive method and it returns -1 if it fails to identify a specific value. In JavaScript, we can use the indexOf() method along with the push() method to remove the duplicate elements from an array.

Example: Remove duplicate elements using indexOf() method

In this example we will utilize the indexOf() method along with the push() method to delete the duplicate elements from the given array:

1
2
3
4
5
6
7
8
9
10
11
12
13

var languages = [«Java», «JavaScript», «Java», «C++», «C», «Java», «C++», «JavaScript», «C++», «Java»];

 function findUniqueElements(languages) {
 var uniqueLanguages = [];
    for(i=0; i< languages.length; i++)
    {
       if(uniqueLanguages.indexOf(languages[i]) === 1) {
       uniqueLanguages.push(languages[i]);
      }
    }
     return uniqueLanguages;
  }  
  console.log(«Resultant Array: «, findUniqueElements(languages));

This example program will serve the below-given functionalities:

  • Firstly, we created an array named “languages” that consists of duplicate elements.
  • Next, we created a function named “findUniqueElements” and we passed the “languages” array to the “findUniqueElements” function as an argument.
  • Next, we created an empty array and named it “uniqueLanguages”.
  • Afterward, we utilized the for loop to traverse through the “languages” array.
  • Next, we utilized the indexOf() method within the if-statement.
  • Within if-statement, the indexOf() method will check whether the value present at the current index of the “languages” array is already there in the “uniqueLanguages” array or not. If yes, then the body of the if-statement doesn’t get executed.
  • While if the value present at the current index of the “languages” array doesn’t exist in the “uniqueLanguages” array then the body of the if-Statement will execute in such a case.
  • Within the body of the if-statement, we utilized the push() method to add the unique elements in the “uniqueLanguages” array.
  • Finally, we utilized the console.log() method to print the array of unique elements:

This is how we can get an array of unique elements using the indexOf() and Push() methods.

How to remove duplicate elements using JavaScript filter() method?

The filter() method in JavaScript creates a new array of only those elements that pass a specific test.

Example: Remove duplicate elements using the filter() method

In this program, we will utilize the filter() method along with the indexOf() method to remove the duplicate elements from an array:

1
2
3
4
5
6

var languages = [«Java», «JavaScript», «Java», «C++», «C», «Java», «C++», «JavaScript», «C++», «Java»];

function findUniqueElements(languages) {
   return languages.filter((element, position) => languages.indexOf(element) === position);
}
console.log(«Resultant Array: «, findUniqueElements(languages));

The above program will perform the following functionalities:

  • Firstly, created an array of duplicate elements.
  • Next, we created a function named finduniqueElements, and passed it the given array i.e., languages.
  • Within the function, we utilized the filter method along with the indexOf() method to get an array of unique elements.
  • Finally, we utilized the console.log() method to print the filtered array on the console as shown in the below-given array:

This is how we can remove the duplicate elements from an array using the filter method.

Conclusion

In JavaScript, several methods can be used to remove duplicate array elements for example, the instanceOf(), filter(), and new Set(). For example, A Set in JavaScript allows us to store the unique elements of any data type such as primitive, or object references. So, we can use the JavaScript Set() to delete the duplicate array elements. Similarly, the filter() method in JavaScript creates a new array of only those elements that pass a specific test. So, the filter() method can be used to get an array of unique elements.

This article explained different methods to remove duplicate elements from an array using some suitable examples.



Source link


Variable size arrays (VLAs) are not forbidden in C++; the iso error is correct. Runtime-sized or variable-sized arrays are the other names for variable-length arrays. The size of these arrays is set at runtime. Among the kinds that can be updated are variable-length arrays and pointers to variable-length arrays. Variably modified types should be defined at either the block or function prototype level. Variable-length arrays are a feature that allows us to allocate a variable-size automóvil array on the stack. In a typedef statement, it can be utilized. From the C++ standard onwards, C enables variable-size arrays. The program below, for example, compiles and runs perfectly in C.

void PrintArray(int n)
{
 int Array[n];
 // ……
}  
int main()
{
PrintArray(8);
}

However, variable-sized arrays are not supported by the C++ standard (until C++11). Array size is a constant expression in the C++11 standard. As a result, the above program may not be an acceptable C++ program. As the GCC compiler has an extension to accommodate them, the program may function with the GCC compiler. As little more, the array size is now a simple expression in C++14 (not constant-expression).

It’s not desirable to have to generate a potentially big array on a stack with limited space. If you are not aware ahead of time, we will write damaging code. Variable-length arrays are not natively supported in C++ because they would necessitate significant type system changes.

Here, in the C++ article, we will show how to overcome the C++ iso forbidden variable-length array error at the compilation time.

Example 1: Program to Implement a variable-length array in C++ With GCC Compiler

Variable-length arrays can choose any size that the user desires, i.e., they can be variable in size. The following is a C++ program for creating variable-length arrays:

We have C++ header files in the first step and the namespace file. After that, we have the program main method, and the main body has the pointer variable declaration as “Array” and the other variable “Arr_Size” declaration. The cout prints the statement that asks the user a number for array size. Then, cin will take the number value from the user. The variable “Array” is called where we have set the size of the array.

Now, we have also requested the array values from the user. The array value will iterate by the for loop till it reaches the array size. Then, the second for loop is used to print the values inside the array, and at the same time, we have deleted the array by using the delete[] expression in the program.

#include <iostream>

#include <string>

 

using namespace std;

int main() {

   int *Array, Arr_size;

   cout<<«Enter array size: «<>Arr_size;

   Array = new int [Arr_size];

   cout<<«Enter array values: «<<endl;

   for (int i = 0; i>Array[i];

   cout<<«Array: «;

   for(int i = 0; i<Arr_size; i++)

   cout<<Array[i]<<» «;

   cout<<endl;

   
   return 0;

}

The shell displays a message for inputting the array size after compilation. When the user input the size of the array then, the shell asks the user to set the values for the array. The size of the array and its elements are accessible as follows. Hence, we can implement a variable-length array in C++ without a forbidden exception.

Example 2: Program to Implement a variable-length array in C++by Using Vectors

The C++ STL provides a vector as an alternative to variable-length arrays. It’s suitable for a variety of applications. It will be more clear with the C++ program, which we have implemented below.

As we have to use vectors in our program. So the most important part is to define the vector as a header file at the top of the code implementation. We have added the vector file in the section of the header.

Within the program main, we have a vector class with type int, and the vectors class has a variable “v.” We have added five elements of type integer in the vector. After that, we have a for loop iteration cycle. Inside the for loop, we have declared an iterator to a vector with a new variable “it.” Then, the “it” variable has a begin and end function for displaying the elements of the vectors.

#include<iostream>
#include<vector>
using namespace std;

int main() {

   vector v;

   v.push_back(10);

   v.push_back(20);

   v.push_back(30);

   v.push_back(40);

   v.push_back(50);

   
   for(vector::iterator it = v.begin(); it != v.end(); it++) {

      cout<< *it <<endl;

   }

   return 0;

}

The above program gives the output like this.

Example 3: Program to Implement a variable-length array in C++ by Using std:: vector

Vectors are used to carry comparable data types in C++. The size of a vector, unlike arrays, can grow dynamically. We can adjust the vector size as needed throughout the program execution. The vector header file must be included in our program to utilize vectors. Merienda the vector library is included in the header file, we can utilize vector as std::vector in the program.

After including the vector library at the top, we have called the std::vector inside the program’s main function. The vector is declared as “numbers” and initialized with the five random numeric values. The variable “number” is again defined, which has three vector elements from the above-given vector container. The std::cout is used to display the length of the vector inside the variable “number” by using the size function.

#include <iostream>

#include <vector>

 

int main()

{
    std::vector numbers = {10, 20, 30, 40, 50};

    numbers = {30, 40, 50};

    std::cout<< «Array Length : « <<numbers.size() << std::endl;

    return 0;

}

The output shows the length of the specified vector array as follows.

Conclusion

Summing up! Here, we have a detailed discussion about variable-length arrays in the introduction. Thus, we learned that C++ forbids variable-length arrays(VLA). We have specified some ways above to implement the variable-length array in C++ and alternative ways of the variable-length array. These might be handy when interacting with the variable-length arrays in C++.



Source link