javascript – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 03:53:52 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 javascript – Java2Blog https://java2blog.com 32 32 Get String Between Two Characters in JavaScript https://java2blog.com/get-string-between-two-characters-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=get-string-between-two-characters-javascript https://java2blog.com/get-string-between-two-characters-javascript/#respond Fri, 27 Jan 2023 10:24:17 +0000 https://java2blog.com/?p=22590

πŸ’‘TL;DR
Use the substring() method to get String between two characters in JavaScript.

function getSubstring(str, start, end) {
  char1 =  str.indexOf(start) + 1;
  char2 =  str.lastIndexOf(end);
  return str.substring(char1, char2);
}
let originalString = "Hello,World!";
let substring = getSubstring(originalString, ',', '!');
console.log(substring);

World

Here, we got String between , and ! in above example.

Using substring() Method

Use the substring() method to extract a substring that is between two specific characters from the given string in JavaScript.

let str = "This is a sample string";
console.log(str.substring(1, 3));
hi

The substring() method allows us to specify a start and end index for the substring we want to extract. Note that in JavaScript, string indices start from 0, so the 2nd character is at index 1, and the 4th character is at index 3.

The above example used substring() to display characters from the specified string. Here, 1 is passed as the first argument to specify the starting position of the substring, and the second argument, 3, represents the substring’s ending position. So, the substring hi was returned between index 1 and 3. Let’s see another example below:

let str = "This is a sample string";
console.log(str.substring(2)); 
console.log(str.substring(4, 1)); 
console.log(str.substring(0, 1)); 
console.log(str.substring(-3));
is is a sample string
his
T
This is a sample string

Here, we can observe that in the first console statement, we passed only the starting position of the string to get all characters of the string starting from index 2 up to the end.

In the second console statement, the start-index was greater than the end-index (4,1). So here, the substring() method itself swapped the parameters as (1,4) and gave results accordingly. And str.substring(0, 1) was only used to get the string’s first character.

We can observe that the last console statement index at the start was -3 (less than 0). So, in that case, the substring started from index 0 to the end. Consider another example below:

let str = "This is a sample string";
let startChar = "a";
let endChar = "g";
let startIndex = str.indexOf(startChar);
let endIndex = str.indexOf(endChar);
let substring = str.substring(startIndex, endIndex);
console.log(substring);
a sample strin

In this example, we first declared a string str with the value This is a sample string. And then, two variables, startChar and endChar, were declared, representing the two characters we wanted to use as the boundaries for our substring. And indexOf() method was used to find the index of the first occurrence of each of these characters in the string.

Next, we used the substring() method to extract the substring between these two indexes. In this case, a sample strin substring was returned.

Note: The above solution assumes that the first character a is guaranteed to be present, and the second character g is also guaranteed to be present after the first character.

The substring that was returned depends on the position of the characters in the string, so if the characters we are searching for are not in the string or are in the wrong order, it will return an empty string or an error. Also, if the startChar is the same as the endChar and the string contains multiple instances of startChar, it will return the substring between the first and second occurrence of startChar.

For better understanding, create a function getSubstring() to get a substring between two characters from the given string. This function getSubstring() takes in three arguments:

  • str is the original string from which we want to extract a substring.
  • start is the starting character of the substring.
  • end is the ending character of the substring.
function getSubstring(str, start, end) {
  char1 =  str.indexOf(start) + 1;
  char2 =  str.lastIndexOf(end);
  return str.substring(char1, char2);
}
let originalString = "Hello,World!";
let substring = getSubstring(originalString, ',', '!');
console.log(substring);
World

Using the indexOf() method, we can determine the position of a value in a string based on the first occurrence, as learned above. On the other hand, the lastIndexOf() method returns the position of a value in a string based on the last occurrence.

In the getSubstring() function definition, char1 contained the index of the first character. And, char2 contained the index of the second character.

Note: 1 is added to the result of the indexOf() method because we do not want to include the first character , in the substring we want to get. However, there is no need to exclude 1 from the lastIndexOf() result because the character at the given end index is already omitted by substring().

Some important points:

  • In JavaScript, if you’re using the indexOf() or lastIndexOf() method to find a substring within a string, and the given values do not exist in the string, both methods will return -1, indicating that the substring was not found.

  • If the first character of the substring does not exist in the string, substring() will return all the characters from the start to the last occurrence of the second character. Let’s see the below example to check this:

const string1 = 'hello:to my;World;of JavaScript!';
const result = getSubstring(string1, '-', ';');
console.log(result);
hello:to my;World

Here, - was not present in string1. That’s why it returned substring from the start to the last occurrence of the ;. Similarly, if the second character is absent, the entire string from the start to the first instance of the first character will be included in the substring. Consider the below example to check this:

const string1 = 'hello:to my;World;of JavaScript!';
const result = getSubstring(string1, ':', '-');
console.log(result);
hello:

Using slice() Method

Use the slice() method to extract a substring that is between two specific characters from the given string in JavaScript.

let str = "Hello to my javaScript world!";
let substring = str.slice(1, 4);
console.log(substring);
ell

The slice() method in JavaScript can extract a substring from a string. This method takes two arguments: The substring’s starting index and ending index.

The above code snippet returned the substring ell between the 2nd and 4th characters of the given string. We can also use the slice() method with only one argument; it will slice the string from the given starting index until the end of the string. Check the below example:

let str = "Hello to my javaScript world!";
let substring = str.slice(9);
console.log(substring);
my javaScript world!

The above example returned substring my javaScript world! using the slice() method from index 9 to the end of the string.

Suppose str.indexOf() returned -1 due to the absence of the required character in the string. In that case, we will increment the value by 1, which results in 0 and allows us to extract characters from the beginning of the string. Check the below example to see how to do this:

const originalStr = "Hello to my javaScript, world!";
const  str= originalStr.slice( 
    originalStr.indexOf('-') + 1,
    originalStr.lastIndexOf(',') );
console.log(str);
Hello to my javaScript

In this code, - was not present in originalStr. So, originalStr.indexOf('-') returned -1; we then added 1, and the start index became 0. That’s why we got the string Hello to my javaScript from the start until we got the second character’s (,) last occurrence`.

Consider a string, Hello to my javaScript, world! and extract a substring between m and ! using the slice() method:

let str = "Hello to my javaScript, world!";
let substring = str.slice(str.indexOf("m")+1,str.indexOf("!"));
console.log(substring);
y javaScript, world

The above code found the index of the first character m and then added 1 to it as we wanted to exclude it from the substring. In the same way, it found the index of the second character ! and then extracted the substring y javaScript, world between these two indexes.

Using split() Method

We can also use the split() method to extract a substring between two specific characters in a string; you will need first to split the string into an array of substrings using the first character as the separator to retrieve the desired substring from the resulting array.

let str = "Hi,Javascript is my favourite";
let substrings = str.split(",");
let substring = substrings[1].substring(0,4);
console.log(substring);
Java

In JavaScript, the split() method is used to split a string into an array of substrings. It can take one or two arguments: A separator (string or regular expression) and a limit.

In this code, we used the split() method to split the string Hi, Javascript is my favourite into the array of substrings ["Hi", "Javascript is my favourite"], then we get the 2nd element from the array as substrings[1] which is Javascript is my favourite. After that, we extracted the first four characters, our desired substring Java.

Now, let’s extract the last element of the string using the Array.pop() method:

let str = "Hi,Javascript is my favourite";
let substrings = str.split(',').pop()
console.log(substrings);
Javascript is my favourite

Here, the split() method is used to split str into the array having two substrings, and then the Array.pop() method is used to remove and return the last element of the array, which is Javascript is my favourite.

Using substr() Method

Use the substr() method in JavaScript to extract a substring from a given string.

let str = "Hello,to my world of JavaScript!";
let sub = str.substr(12, 5); 
console.log(sub);
world

The substr() method takes two parameters: the starting index of the substring and the length representing the number of characters we want to extract.

In the above example, the substr() method was used to extract the substring world from the string Hello, to my world of JavaScript!. Here, we wanted to get a substring from index 12 having 5 characters.

Consider a scenario where we want to get only the first character of the string:

let myStr = "Hello,to my world of JavaScript!";
let my_subStr = myStr.substr(0, 1);
console.log(my_subStr);
H

We can observe first character H from myStr was returned because we have passed 0 as the starting index and 1 as the length of the substring. And if you want to get only the last character of the string, then the following solution is for you:

let myStr = "Hello,to my world of JavaScript!";
let my_subStr = myStr.substr(-1, 1);
console.log(my_subStr);
!

In the above code snippet, -1 was used as the starting index because we wanted to extract the substring from the end with a 1 character. Now, let’s extract the last 11 characters of myStr.

let myStr = "Hello,to my world of JavaScript!";
let my_subStr = myStr.substr(-11, 11);
console.log(my_subStr);
JavaScript!
]]>
https://java2blog.com/get-string-between-two-characters-javascript/feed/ 0
Return Boolean from Function in JavaScript https://java2blog.com/return-boolean-from-function-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=return-boolean-from-function-javascript https://java2blog.com/return-boolean-from-function-javascript/#respond Tue, 27 Dec 2022 07:12:30 +0000 https://java2blog.com/?p=22027 Using the Boolean() Function

To get a Boolean from a function in JavaScript:

  • Create a function which returns a Boolean value.
  • Use the Boolean() function to get a Boolean value from the function created in the previous step.
function func(){
  return Boolean(10>5);
}
console.log(func());
true

We used the Boolean(), a built-in function in JavaScript, to check if a variable or an expression is true or false and returned its value using the return statement. Also, we can write the above example without Boolean() like:

function func(){
  return (10>5);
}
console.log(func());
true

If you are not aware of Boolean values and want to know how we can declare them, then we have you covered. A Boolean value can be one of these in programming languages:

  • Yes or No
  • True or False
  • 0 or 1

However, there is only one data type for Boolean values in JavaScript: true or false. In JavaScript, we can declare a boolean variable with and without using let/var. Have a look at the example below to see JavaScript compiler behaviour.

function  boolfunc(){
    return true;
}
isBoolean1 = boolfunc();
console.log(typeof(isBoolean1)); 

let isBoolean2 = boolfunc();
console.log(typeof(isBoolean2)); 

var isBoolean3 = boolfunc();
console.log(typeof(isBoolean3));
boolean
boolean
boolean

We can observe that the variable’s data type declared with/without let/var is a boolean.

Use the Boolean() Function with Truthy/Falsy Values

Some values are Truthy Values in JavaScript, which are always true; we can find these values below:

  • Except 0, -0, and NaN, other numbers are true.
  • Symbols turn into true.
  • All objects become true.
console.log("10 is " + Boolean(100));
console.log("1.6 is " + Boolean(3.14));
console.log("-15 is " + Boolean(-15));
console.log(Boolean("Hello"));
console.log(Boolean('false'));
console.log(Boolean(1 + 7 + 3.14));
console.log(Boolean([]));
console.log(Boolean({}));
10 is true
1.6 is true
-15 is true
true
true
true
true
true

We can observe above that anything with some value, including expressions except 0, was true. Note that even the string false was also true. In JavaScript, the falsy values are those that always return false; these values are listed below:

  • false
  • null
  • undefined
  • 0
  • ""
  • (empty string)
  • NaN (not a number)
console.log(Boolean(''));
console.log(Boolean(0));
console.log(Boolean(-0));
console.log(Boolean(undefined)); 
console.log(Boolean(null));
false
false
false
false
false

So now, we can define a function based on the type of argument it is getting and wrap our return value in the Boolean() function to return a Boolean value from a function.

Using Comparison Operator

To get a Boolean value from a function:

  • Create a function isEqual() and evaluate its value using the if statement with the === operator.
  • Depending on the if condition, return true or false.
    Strict equality operator === returns either true or false depending on the value of two operands.
function isEqual(x,y) {
 if (x === y) {
  return true;
 } else {
  return false;
 }
}

console.log(isEqual(12,6))
console.log(isEqual(5,5))
false
true

We can also compare without using the if-else block, giving the same result as the above example.

function isEqual(x,y) {
 return x === y;
}

console.log(isEqual(12,6));
console.log(isEqual(5,5));
false
true

Now, let’s create another function related to a real-life example that determines whether someone is eligible for a job and see how to return a Boolean value from a function there.

The isEligibleForJob() function takes an age argument and returns whether the person is old enough to apply for a job. First, a check is made to see if the age is equal to or greater than 25. Based on that comparison, it will return true or false.

function isEligibleForJob(age) {
 return age >= 25;
} 

console.log(isEligibleForJob(18));
console.log(isEligibleForJob(25));
false
true

We can also write it using the arrow function as follows:

const isEligibleForJob = (age) => age >= 25;
console.log(isEligibleForJob(18)); // false
console.log(isEligibleForJob(25)); // true

In the above code, => represented the Fat Arrow of an arrow function while >= is an operator which means greater-than and equal-to. Alternatively, we can also use the Ternary operator ?: and an Arrow Function to return a Boolean value from a function.

const isEligibleForJob = (age) => age < 25 ? false: true;
console.log(isEligibleForJob(18)); //false
console.log(isEligibleForJob(25)); //true

We noticed that the above code returned two Boolean values, false and true. Now, think of a scenario where we have to work with Booleans as objects and return a Boolean value after making a comparison with those objects in a function. Let’s learn how we can do it.

Use ==/=== Operator to Get Boolean Using Booleans as Objects

To get a Boolean using Booleans as objects:

  • Write a function which takes a Boolean type value as an argument.
  • Use the new keyword to create a Boolean object.
  • Use == operator to do comparison and return the resulted value.
function comparison(x) {
 let y = new Boolean(false);
 return x==y;
} 

console.log(comparison(false));
true

In JavaScript, we can define an object using a new keyword. In the above example, we wrote a function comparison(), which took a variable x as an argument and created an object y.

After creating an object, it compared x (Boolean value) and y (Boolean object) to see what Boolean value it would return. After comparison, we received true as an output.

Similarly, we can use === operator as follows:

function comparison(x) {
 let y = new Boolean(false); 
 return x===y;
} 

console.log(comparison(false));
false

Now observe the result using the === operator; x (a Boolean value) and y (a Boolean object) are not equal. It is because the === operator not only compared the values but their data type as well.

There can be a situation where we want to get a Boolean value from a function after comparing two Boolean objects. Let’s see how we can do it using comparison operators.

Use ==/=== Operator to Compare Two Boolean Objects

To get a Boolean value from a function after comparing two Boolean objects:

  • Write a function which creates two Boolean-type objects using the new keyword.
  • Use == operator to compare both boolean objects and return resulted value.
  • Now, call the function (created in the first step) to see what it returns after comparing two Boolean objects.
function compareObjects() {
 let y = new Boolean(true);  //y is boolean object 
 let x = new Boolean(false) ;  // x is a boolean object
 return x==y;
} 

console.log(compareObjects()); //false

We can see that the output is false when we compare two objects. Now, let’s see how the === operator will behave.

function compareObjects() {
 let y = new Boolean(true);  //y is boolean object 
 let x = new Boolean(false); // x is a boolean object
 return x===y;
} 

console.log(compareObjects());//false

It also returned false. We can observe comparing two JavaScript objects that always return a false value. That is the reason avoiding Boolean objects is good because it gives unexpected results. Making a comparison of Boolean variables and Boolean objects is not safe to do.

That’s all about how to return boolean from function in JavaScript

]]>
https://java2blog.com/return-boolean-from-function-javascript/feed/ 0
Create Array from 1 to 100 in JavaScript https://java2blog.com/create-array-from-1-to-100-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-from-1-to-100-javascript https://java2blog.com/create-array-from-1-to-100-javascript/#respond Fri, 23 Dec 2022 13:15:20 +0000 https://java2blog.com/?p=21776 Use for Loop

To create the array from 1 to 100 in JavaScript:

  • Use a for loop that will iterate over a variable whose value starts from 1 and ends at 100 while the variable’s value is incremented by 1 in each iteration.
  • Inside the for loop, use the push() method to insert a value to an array.
  • Use the log() method to display the array on the console.
var my_array = [];

    for (var i = 1; i <= 100; i++) {
       my_array.push(i);
    }

    console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

Using loops is useful when we are supposed to perform the same function repeatedly. For example, we used a for loop because we wanted to insert a value into an array often; this value can be the same or different, and we are inserting a different value in each iteration.

The for loop contained three expressions: the first expression is var i = 1, the second is i <= 100, and the third is i++. The first expression, var i = 1, set the value of variable i to 1 before starting the loop, and this expression got executed once.

The second expression, i <= 100, demonstrated the condition to validate the first expression and executed the loop. This condition explained that the loop would be executed if the value of i is less than or equal to 100. Otherwise, it would throw the pointer out of the for loop.

The third expression, i++, is used to increment the value of i. Finally, inside the for loop, we used the push() method, which can add a new item to an end of the array, changes the array’s length and returns the new size/length of the array.

Finally, we used the console.log() method to display the array values on the console. In JavaScript, we have to be careful about the following points while using a for loop:

  1. The first expression is optional, and we can omit it. In that case, we can initialize the variable’s value before writing the loop.

    Note that we can initialize multiple variables in the first expression; this case would be helpful if we have to create two arrays, one from 1 to 100 and the second from 101 to 200 using one for loop.

  2. The second expression is optional, and we can omit that. Remember, if we don’t want to have the second expression, we must write a break inside the for loop; otherwise, it would be a never-ending loop and crash the browser.

  3. The third expression can also be omitted, and we can increment the variable’s value inside the for loop.

You may have noticed that using the for loop requires more lines of code and care. What if we can have some shorter ways of achieving the same results? Let’s explore them below.

Use Array.from() with Array.keys()

If we are using ES6 (ECMAScript6), then we can use this approach to create the array from 1 to 100 in JavaScript:

  • Use the Array() constructor to instantiate the Array class or we can say to create an Array object.
  • Pass an integer ranging from 0 to 2^(32 - 1) (inclusive) to the Array() constructor. It will create a new array with a length property set to the number we passed in Array().
  • Use the .keys() method to get an Array Iterator Object with the array’s keys.
  • Use the .from() method to get an array from an iterable object that we get using the .keys() method in the previous step.
  • Use the .slice() method to specify the start position.
var my_array = Array.from(Array(100+1).keys()).slice(1)  
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

This code seems challenging to understand but believe me, it’s straightforward. So let’s break it down into chunks to understand clearly.

We used the Array() constructor to create an Array object and passed it 101 (why is it 101, we will see that in a while). In this way, it created an object of Array where its length property is set to 101. So now, the length of the array is 101, but array elements are empty slots.

console.log(Array(100+1).length) // 101
console.log(Array(100+1)) // [ <101 empty items> ]

Next, we chained the Array(100+1) with the keys() method to get an Array Iterator Object with all the array keys. For learning purposes, we can print the keys as follows.

for(let i of Array(100+1).keys() ){
   console.log(i)
}
//0,1,2,3,4,5,6,..., 98,99,100

Note that the keys started from 0 to length-1. Taking you back to where we talked about why it is 101? Because we want to have 100 as the last element, we passed 101, which made length-1 as 100 (101-1).

After that, we passed this iterable object (returned by Array(100+1).keys()) to the Array.from() method, which produced an array from the given iterable object.

At this point, we had an array starting from 0 to 100, but we wanted to get an array starting from 1. For that, we used the slice() method and specified the starting position as 1; by default, it was 0.

We now have an array from 1 to 100.

Use Array.from() with Array Constructor

To create the array from 1 to 100 in JavaScript:

  • Use the Array() constructor to instantiate the Array class. Pass the 100 as an argument to the constructor; it will create a new array with a length property set to the 100 we passed in Array().
  • Write an arrow function to increment an index by 1.
  • Map the arrow function to the object by passing the object and arrow function (created in the first and second steps) to the Array.from() method to get an array starting from 1 to 100.
var my_array = Array.from(Array(100), (_, index) => index + 1);
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

Here, we used the Array() constructor to create an Array object where the object’s length property is set to 100. Then, we created an arrow function as (_, index) => index + 1 where the left part of the => denotes the input and the right part of the => applies the transformation to this input.

Note that the underscore (_) is a valid identifier in JavaScript and is used to identify the object. Next, we passed the Array object and arrow function (_, index) => index + 1 to the Array.from() method to create an array from 1 to 100.

Use Array.from() with length Property

To create the array from 1 to 100 in JavaScript:

  • Create an object with its length property set to 100.
  • Write an arrow function to increment an index by 1.
  • Map the arrow function to the object by passing the object and arrow function (created in the first and second steps) to the Array.from() method to create an array starting from 1 to 100.
var my_array = Array.from({length: 100}, (_, index) => index + 1);
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

This code is similar to the last code example except for one difference; we created a JavaScript object as {length: 100} where the object’s length property is set to 100.

Next, we used an arrow function, which is already explained while using Array.from() with Array Constructor. Finally, we passed the {length: 100} object and arrow function (_, index) => index + 1 to the Array.from() method to create an array from 1 to 100.

Use Array.from() with fill() Method

To create the array from 1 to 100 in JavaScript:

  • Use the Array() constructor to create an Array object of size 100.
  • Use the fill() method to fill all array elements’ slots with the values received from the arrow function.
  • Use Array.from() to get an array from the specified iterable object.
var my_array = Array.from(Array(100).fill(), (_, i) => i+1);
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

In previous examples, we have already learned about the Array.from(), Array() constructor, arrow function, and _ identifier.

Here, we used the fill() method, which took the value from the arrow function and filled the array’s current slot. Note that the fill() method overwrites the original array.

We can use the fill() method with the map() method as follows:

var my_array = Array(100).fill().map((_, i) => i+1);
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

The map() created the new array by executing the function (here, it is the arrow function) for every array element. Remember that the map() is called a function only once for every element in the array.

Further, it did not execute a function for empty elements and did not modify the original array.

Use ... Operator

To create the array from 1 to 100 in JavaScript:

  • Use spread operator (...) with Array(100).keys() to have all the keys of an array of size 100.
  • Use the map() function to create a new array by running the specified function for every array element.
var my_array = [ ...Array(100).keys() ].map( i => i+1);
console.log(my_array)
[
  1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
  13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
  25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
  37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
  49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
  73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
  85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
  97, 98, 99, 100
]

We have already learned about Array() constructor, .keys(), map(), and arrow function. Here, we used ES6’s feature named spread operator (...) to accept an iterable and expand its elements into individuals.

Then, we enclosed it into square brackets as [ ...Array(100).keys() ] to make an array of those individual elements that are from 0-99. To have an array from 1-100, we created an arrow function called by the map() method only once for every element in the array.

]]>
https://java2blog.com/create-array-from-1-to-100-javascript/feed/ 0
Get Index of Max Value in Array in JavaScript https://java2blog.com/get-index-of-max-value-array-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=get-index-of-max-value-array-javascript https://java2blog.com/get-index-of-max-value-array-javascript/#respond Fri, 23 Dec 2022 11:43:18 +0000 https://java2blog.com/?p=21844 Using indexOf() with Math.max() Method

To get an index of the max value in a JavaScript array:

  • Use the Math.max() function to find the maximum number from the given numbers. Here, we passed an array and used the spread operator (...) to expand the array into individual elements.
  • Use the .indexOf() function to get the index of the maximum value that we received from the previous step.
var my_array = [5,6,7,2,8,0]
var result = my_array.indexOf(Math.max(...my_array));
console.log(result)
4

We used the Math.max() for this example to get the maximum number from the given numbers as input. Here, we gave an array as an input and used the spread operator (...) to expand the array into individual elements, which means [5,6,7,2,8,0] will turn into 5,6,7,2,8,0.

Math.max() returns NaN if any of the values from the specified numbers would be NaN or converted into NaN. The Math.max() returns -infinity if no parameter is given.

Next, we used the .indexOf() to get the index of the maximum value that we got from the Math.max() function. Always keep the following points in mind while using the .indexOf() function with an array in JavaScript:

  • It returns the first index/position of the given value. So, for instance, if we had two 8 in our array, then the maximum number would be 8, but .indexOf() would return the index of the first maximum value, which is the index of the first 8 in the array.
  • It returns -1 if no value is found.
  • By default, it starts searching from the first element and continues till the end, but we can start it from a user-defined position by specifying the start value. This way, it will start searching from the start point and move from left to right.
  • For the negative start value, it counts from the last element but still searches from left to right.

If you don’t want to use the spread operator (...) to pass the array to the Math.max() method, then we can use Math.max.apply() as follows. Remember, we can not pass the array directly to Math.max().

var my_array = [5,6,7,2,8,0]
var result = my_array.indexOf(Math.max.apply(Math,my_array));
console.log(result)
4

Here, we passed the my_array array to the apply() method directly, which applied the array as parameters to an actual function, Math.max() here. You might have a question about how .apply() worked here.

Here, the Math.max.apply(Math,my_array) can be understood as Math.max(5,6,7,2,8,0). This is how the .apply() method applied the array as parameters to an actual function.

Using for loop

To get an index of the maximum value in a JavaScript array:

  • Initialize maximum value with first element of the array.
  • Iterate over the array using for loop.
  • In each iteration, compare if current element is greater than maximum value.
  • If yes, update the maximum value and its index.
  • Once loop is finished, we will get index of maximum value in the array.
function indexOfMaximumValue(my_array) {
    if (my_array.length === 0) {
        return -1;
    }
    else{
      var maximumValue = my_array[0];
      var maxIndex = 0;

      for (var i = 1; i < my_array.length; i++) {
          if (my_array[i] > maximumValue) {
              maxIndex = i;
              maximumValue = my_array[i];
          }
      }
      return maxIndex;
    }
}

var my_array = [5,6,7,2,8,0]
var result = indexOfMaximumValue(my_array)
console.log(result)
4

First, we wrote a function named indexOfMaximumValue(), which took an array called my_array as a parameter. Inside this function, we used the if statement with strict equality (===) operator to check if the array.length is equal to 0.

If the if statement satisfied the condition, we returned -1 and exited from the indexOfMaximumValue() function; otherwise, we could jump to the else block. In the else block, we declared two variables named maximumValue & maxIndex holding the my_array‘s first element (which is at index 0) and 0, respectively.

Next, we used a for loop, which iterated from 1 to my_array.length-1. In every iteration, we used an if statement with the> operator to check if the array’s current element is greater than the maximumValue; if it is, then update the values of maxIndex and maximumValue.

Once the for loop was over, we returned the index we were updating in maxIndex. Next, we invoked the indexOfMaximumValue() function by passing an array as a parameter, and lastly, we printed the returned result on the console.

Using reduce() Function

To get an index of the maximum value in a JavaScript array:

  • Use the .reduce() function to get the maximum value index from the given array.
var my_array = [5,6,7,2,8,0]
var result = my_array.reduce((iMax, currentValue, currentIndex, arr) =>
                               currentValue > arr[iMax] ? currentIndex: iMax, 0);
console.log(result)
4

Here, we used the .reduce() method to figure out the index of the maximum number from the specified array as an input. The .reduce() function took two arguments; the first was the function, and the second was 0. Let’s understand the function and second argument below:

  • iMax – It was the best index yet, which meant the index of the maximum value so far. On the first iteration, the iMax = 0 because the second argument to the .reduce() function was 0.
    Why is it 0? It is because we assumed that the first element of the array was the maximum number, so we can not omit the second argument in our case.
  • currentValue – The currently tested value from the array.
  • currentIndex – It denotes the currently tested index.
  • arr – It is our array [5,6,7,2,8,0].

The first argument of the .reduce() method performed the reduction operation. The job of this reduction function was to combine/reduce two values into one value and return that reduced value.

Note that the functions used with the .reduce() function are not the same as the functions used with map() and forEach(). The currentValue, currentIndex, and arr were passed as the second, third and fourth parameters. The first parameter was the reduction’s accumulated result so far.

While invoking this function the first time, this first argument was the initial value we passed as the second argument to .reduce(); on subsequent calls, it was the value returned by the function’s previous invocation.

When we invoked the .reduce() function without any initial value, it used the array’s first element as an initial value. So, the first call to the reduction function will have the first and second elements of the array as its first and second arguments, respectively.

Using _.indexOf() with _.max() Method

To get an index of the maximum value in a JavaScript array:

  • Use the require() method to import the Underscore library.
  • Use _.max() to find the maximum number from the given array.
  • Use _.indexOf() to get an index of the maximum number we got from the previous step.
var _ = require('underscore');
var my_array = [5,6,7,2,8,0]
var result = _.indexOf(my_array, _.max(my_array))
console.log(result)
4

Here, we used Underscore library to simplify things. To take advantage of this library, we used the require() method to import it by specifying the library name as an argument.

After declaring and initializing an array, we used the _.max() method that took the my_array as a parameter. It took the element from the given array one by one and compared the elements to find the greatest number in the my_array. The _max() ended after iterating over and comparing all the array elements.

Next, we used the _.indexOf() method to get an index of the element whose position/index we wanted to find. It started from 0 to count the index of the elements in the my_array. Remember, it will return -1 if unable to find the required element (returned by the _.max(my_array)) in the my_array (which is passed as a first argument).

Until now, we have learned various approaches for finding the maximum value index from an unsorted array. So, let’s see what we can do in a sorted array.

Using sort() with indexOf() Method

To get an index of the maximum value in a JavaScript array:

  • Use the spread operator to create the copy of the array.
  • The copied array from the last step is chained with the .sort() method to sort the array in descending order.
  • After sorting, use .indexOf() to find the index of the first element, which is at index 0.
var my_array = [5,6,7,2,8,0]
var copied_array = [...my_array]
var sorted = copied_array.sort((a,b) => b - a)
var result = my_array.indexOf(sorted[0])
console.log(result)
4

After declaring and initializing the array, we used the ... to make a copy of the my_array. How? The spread operator turned [5,6,7,2,8,0] to 5,6,7,2,8,0 but wrapping it around [] made it an array again that we stored in the copied_array variable.

Next, we chained copied_array with the sort() method to sort in descending order. Doing so gave us the maximum value at the 0 index. Then, we used .indexOf() to grab the index of the first element, which was at index 0.

That’s all about how to get index of max value in array in JavaScript

]]>
https://java2blog.com/get-index-of-max-value-array-javascript/feed/ 0
Update Key with New Value in JavaScript https://java2blog.com/update-key-with-new-value-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=update-key-with-new-value-javascript https://java2blog.com/update-key-with-new-value-javascript/#respond Thu, 22 Dec 2022 12:56:46 +0000 https://java2blog.com/?p=21932 Using Bracket Notation

We can use bracket notation to update the key with the new value in Python.

Update Single Key with New Value

To update a single key with a new value, use bracket notation to read it and update it with a new value.

let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
user['age']+=1;
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: 'Anonymous', email: '@gmail.com', age: 37, city: 'London' }

Bracket notation in JavaScript is a way to access properties of an object or elements within an array using square brackets using the object[property] syntax.

Property names must be valid JavaScript identifiers enclosed in quotes to access object properties. Array indices must be integers to access array elements. It is similar to dot notation but more flexible because developers can use strings, variables, and expressions within the brackets.

Bracket notation also updates the values of the property. For example, we used bracket notation to access the age of the array user and incremented it by 1 using user["age"]+=1.

Update Multiple Keys with New Values

To update multiple keys with new values, use bracket notation to access the elements and update them with new values.

let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
user['age']+=1;
user["city"] = "Paris"
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: 'Anonymous', email: '@gmail.com', age: 37, city: 'Paris' }

We already discussed bracket notation while explaining the code snippet for updating a single key using bracket notation. In this section, we used it to update multiple keys with new values. For example, we updated the age and city of the user.

Using Dot Notation

We use dot notation to update the key with the new value in Python.

Update Single Key with New Value

To update a single key with a new value, use dot notation to read the element and update it with a new value.

let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
user.age+=1;
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: 'Anonymous', email: '@gmail.com', age: 37, city: 'London' }

Dot notation in JavaScript is a way to access object properties and methods directly by name. It is more straightforward, more readable, and more efficient than bracket notation.

It uses a period (.) to separate the object and its property. So the syntax looks like this: object.property. It is also great for updating property values quickly and easily.

For example, we used dot notation to access the age of the array user and incremented it by 1 using user.age+=1.

Update Multiple Keys with New Values

To update multiple keys with new values, use dot notation to access the elements and update them with new values.

let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
user.age+=1;
user.city = "Paris"
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: 'Anonymous', email: '@gmail.com', age: 37, city: 'Paris' }

We discussed dot notation while explaining the code snippet for updating a single key using dot notation. In this section, we used it to update multiple keys with new values. For example, we updated the age and city of the user.

We have learned how to update single/multiple keys with new values in JavaScript. Now, think of a project where we have to update all keys with new values; let’s learn how to do that.

Using forEach() Method

Update All Keys with New Values

To update all keys with new values using the forEach() method:

  • Use the Object.keys() method to create an array of keys of the object.
  • Use the forEach() method to iterate over the array and update its values.
let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
Object.keys(user).forEach((key) => {
    user[key] = '';
});
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: '', email: '', age: '', city: '' }

The Object.keys() method in JavaScript retrieves the names of all the enumerable properties of an object so that we can access and manipulate their values.

It returns an array of strings containing the names of all properties of the specified object. It is more efficient than looping through the entire object. For example, we used this method to extract the keys from the user.

JavaScript’s forEach() method allows developers to iterate over an array or an object and execute a provided function once for each element. For example, we can use this method to add elements to an array, modify existing elements, or count elements.

For example, we applied this method to the array of keys of the user to update the values with the empty strings.

Using map() Method

Update All Keys with New Values

To update all keys with new values using the map() method:

  • Use the Object.keys() method to create an array of keys of the object.
  • Use the map() method to iterate over the array and update its values.
let user = {
    "name": "Anonymous",
    "email": "@gmail.com",
    "age": 36,
    "city": "London",
};
console.log(user);
Object.keys(user).map((key) => {
    user[key] = '';
});
console.log(user);
{ name: 'Anonymous', email: '@gmail.com', age: 36, city: 'London' }
{ name: '', email: '', age: '', city: '' }

We have already discussed the Object.keys() method while explaining the code snippet for using the forEach() method.

In this section, we used the map() function that processes each element of the array and executes the provided function on them. For example, we applied this method to the array of keys created with the Object.keys() method to update the values with the empty strings.

]]>
https://java2blog.com/update-key-with-new-value-javascript/feed/ 0
Format Phone Number in JavaScript https://java2blog.com/format-phone-number-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=format-phone-number-javascript https://java2blog.com/format-phone-number-javascript/#respond Wed, 21 Dec 2022 12:32:42 +0000 https://java2blog.com/?p=21935 Using match() Method

We use the match() method to format a phone number in JavaScript.

Format Without Country Code

To format the phone number without country code:

  • Use the replace() method with a regular expression /\D/g to remove non-numeric elements from the phone number.
  • Use the match() method with a regular expression to match and create an array with combinations of 3, 3, and 4 digits.
  • Use the if statement to check if the array is not null.
  • Use the + operator to concatenate the elements of the array.
let phone_number = '1234s5s67890'
console.log('Input: '+phone_number)

phone_number = phone_number.replace(/\D/g, '')
let match = phone_number.match(/^(\d{3})(\d{3})(\d{4})$/)

if (match) {
    phone_number = '(' + match[1] + ') ' + match[2] + '-' + match[3]
}

console.log('Output: '+phone_number)
Input: 1234s5s67890
Output: (123) 456-7890

JavaScript’s replace() method finds a specific part of a given string and replaces it with different text. We can use it with regular expressions to make complex replacements.

A regular expression is a special syntax that creates patterns in strings to find, match, and replace them more precisely. They are composed of characters and operators that define a pattern.

For example, we used the replace() method with the regular expression /\D/g to remove all the non-numeric elements from the phone_number by replacing them with empty strings. Here, \D is equivalent to [^0-9] while the g flag is used for the global match.

The match() method in JavaScript is a powerful tool for manipulating strings. It searches for a specific pattern or character within a string and returns an array of matches or null if no matches are found.

The pattern can either be a regular expression or a substring. We can use this method for validation, such as checking for valid e-mail address formats. For example, we used it to format the phone_number.

Inside the match() method, we specified the regex expression as /^(\d{3})(\d{3})(\d{4})$/ where (\d{1}) sets one digit at an index of the match array, (\d{3}) sets three digits, and (\d{4}) sets four digits.

Here is diagram to understand regex better.

Format phone number in JavaScript

After using an if statement to check if the match array is not null, we used the + operator to concatenate the elements of the match array to get the formatted phone_number.

Format with Country Code

To format the phone number with the country code:

  • Use the replace() method with a regular expression /\D/g to remove non-numeric elements from the phone number.
  • Use the match() method with a regular expression to match and create an array with combinations of 3, 3, and 4 digits where the country code comes at the first index.
  • Use the if statement to check if the array is not null.
  • Use the ternary conditional statement to set the country code to +1 if the value at the array’s first index is not null.
  • Use the + operator to concatenate the elements of the array with the leading country code.
let phone_number = '+11234s5s67890'
console.log('Input: '+phone_number)

phone_number = phone_number.replace(/\D/g, '')
let match = phone_number.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)

if (match) {
    let country_code = (match[1] ? '+1 ' : '')
    phone_number = country_code + '(' + match[2] + ') ' + match[3] + '-' + match[4]
}

console.log('Output: '+phone_number)
Input: +11234s5s67890
Output: +1 (123) 456-7890

We have already discussed the replace() method, regular expression, and the match() method while explaining the code snippet for using this method to format the phone number without the country code.

In this section, we used the regular expression (1|)? inside the match() method to find any of its alternatives in the phone_number. If nothing is found, it sets the value of the first index of the match to null.

We used the ternary conditional statement inside the if statement to set the country code to +1 if the value at the first index of the match is not null. After that, we used the + operator to concatenate the elements of the match to create a formatted phone_number.

That’s all about how to format phone number in JavaScript.

]]>
https://java2blog.com/format-phone-number-javascript/feed/ 0
Remove Word from String in JavaScript https://java2blog.com/remove-word-from-string-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=remove-word-from-string-javascript https://java2blog.com/remove-word-from-string-javascript/#respond Wed, 21 Dec 2022 03:40:12 +0000 https://java2blog.com/?p=21904 Using replace() Method

We can use the replace() method to remove a word or words from a string in JavaScript.

Remove a Single Occurrence of a Word

To remove a single occurrence of a word from a string, use the replace() method to replace the word in the string with an empty string.

var my_string = "This program removes abc word from a string.";
console.log("Original String: " + my_string);
var word = 'abc';
my_string = my_string.replace(word,"");
console.log("After removal: " + my_string);
Original String: This program removes abc word from a string.
After removal: This program removes  word from a string.

The replace() method in JavaScript is a string method that searches and replaces the occurrences of a given substring with another substring and returns the updated string. It holds arguments:

β€’ The pattern represents a specific set of characters inside an existing string that needs replacing.

β€’ The replaceValue states what should overwrite over the pattern.

We used the replace() method to overwrite an empty string over the pattern abc to remove the pattern.

Remove Multiple Occurrences of a Word

To remove multiple occurrences of a word from a string, use the replace() method with a RegExp to replace it with an empty string.

var my_string = "This program removes abc abc words from a string.";
console.log("Original String: " + my_string);

my_string = my_string.replace(/abc/g,"");
console.log("After removal: " + my_string);
Original String: This program removes abc abc words from a string.
After removal: This program removes   words from a string.

We have already discussed the replace() method while explaining the code snippet for removing a single word from the string using the replace() method. In this section, we used the method with a RegExp expression.

The RegExp expression RegExp is a sequence of characters that constructs a search pattern used to perform complex search and replace operations on strings in JavaScript. The patterns are built using the RegExp syntax. It can have several parameters enclosed in forward slashes /.

We provided the replace() method with /abc/g as a regular expression to search it into the string and replace it with an empty string to remove it. Here, the pattern was abc that we wanted to replace with an empty string, while the g flag is used for global search, which means it searched for all instances in String.

Using substr() Method

To remove word from string in JavaScript:

  • Use the substr() method to make two substrings by splitting the string into two parts, excluding the word from it.
  • Use + operator to concatenate the two substrings.
var my_string = "This program removes abc word from a string.";
console.log("Original String: " + my_string);
var word = 'abc';

var substring1 = my_string.substr(0,my_string.indexOf(word)-1);
var substring2 = my_string.substr(my_string.indexOf(word) + word.length);

my_string = substring1 + substring2;
console.log("After removal: " + my_string);
Original String: This program removes abc word from a string.
After removal: This program removes word from a string.

The JavaScript substr() method extracts a specified number of characters from the beginning or end of a string. It returns the part of the string between the start and count parameters but does not change the original string object. The arguments it holds are:

  • The start of the integer type denotes what position in a given String object we wish to begin extracting characters from.
  • An optional length of integer type represents how many characters should be extracted after the start (if no length argument is included, it will default to full end-string).

We used the substr() method to make substring1 and substring2 from the my_string:

  • For the substring1, we specified the start as 0 and the length up to 1 less than the starting index of the word we wanted to remove using the indexOf() method.
  • For the substring2, we set the start with the sum of the starting index of the word and the length of that word using the indexOf() and length functions, respectively.

After successfully creating two substrings, we used the + operator to concatenate the two substrings into my_string.

That’s all about how to remove word from String in JavaScript.

]]>
https://java2blog.com/remove-word-from-string-javascript/feed/ 0
Write Array to CSV in JavaScript https://java2blog.com/write-array-to-csv-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=write-array-to-csv-javascript https://java2blog.com/write-array-to-csv-javascript/#respond Sat, 17 Dec 2022 19:50:29 +0000 https://java2blog.com/?p=21922 Using toString() method

To write array to CSV in JavaScript:

  • Declare an array with some elements in it.
  • Use the toString() method. This method will convert the array into the CSV(Comma-Separated Value).
  • Finally, console the value to see the result.

Follow the below program:

const myArray = ['Cricket', 'ICC', 'Football', 'FIFA']
const arrayToCsv = myArray.toString()

console.log(typeof(arrayToCsv))

Output:

Cricket,ICC,Football,FIFA

Using join() method

To write array to CSV in JavaScript:

  • Declare an array that consists of some elements
  • Use the join() method and pass the symbol as an argument that will be used in joining the elements. This method returns the result in the string form.
  • Finally, console it to see the result.

Follow the below program:

const myArray = ['Cricket', 'ICC', 'Football', 'FIFA']
const arrayToCsv = myArray.join(',')

console.log(arrayToCsv)

Output:

Cricket,ICC,Football,FIFA

We used comma(,) to join the array elements. In your case, you can use other symbols also.

Our purpose is to write CSV(Comma-Separated Value) from an Array in JavaScript.

Using valueOf() method

To write array to CSV in JavaScript:

  • The valueOf() method works exactly as the toString() method. You can follow the steps that are followed while using the toString() method. All you need to do is to use the valueOf() instead of toString().

Follow the below program:

const myArray = ['Cricket', 'ICC', 'Football', 'FIFA']
const arrayToCsv = myArray.valueOf()

console.log(arrayToCsv)

Output:

Cricket,ICC,Football,FIFA

Write Array of Objects to CSV

To write Array of Objects to CSV:

  • Declare an array that consists of some objects.
  • Define the column headers and then use the spread(…) operator as well as the map() function to separate the key-value pairs from the array.
  • Finally, use another map() function and join() method to separate the values with a comma(,)
  • Console.log() them to see the output.

Follow the below program:

const arrayOfObject = [
    { stdId: 1, stdName: "Rahul" },
    { stdId: 2, stdName: "John" },
    { stdId: 3, stdName: "Virat" }
  ]

  const arrayOfObjectToCSV = [
    [
      "Student ID",
      "Student Name"
    ],
    ...arrayOfObject.map(data => [
      data.stdId,
      data.stdName
    ])
  ]
   .map(el => el.join(","))
   .join("\n")

console.log(arrayOfObject)
console.log(typeof(arrayOfObject))
console.log(arrayOfObjectToCSV)
console.log(typeof(arrayOfObjectToCSV))

Output:

[
  { stdId: 1, stdName: 'Rahul' },
  { stdId: 2, stdName: 'John' },
  { stdId: 3, stdName: 'Virat' }
]
I am --> object   

Student ID,Student Name
1,Rahul
2,John
3,Virat
I am --> string

We used the spread(...) operator to extract the key-value pair and used the map() function to convert the Object data into the array.

Now, we get the element into an array form. We used the mapping function and the join() method in this array. This will join the array elements with a comma(,) and convert them into the string.

Another join() method is used to separate the strings into a new line.

Finally, We consoled arrayOfObject as well as used the typeOf() method. It shows that it is an Object.

We consoled arrayOfObjectToCSV and also used the typeOf() method here. It shows String.

That’s all about how to write array to CSV in JavaScript.

]]>
https://java2blog.com/write-array-to-csv-javascript/feed/ 0
Fill Array with Random Numbers in JavaScript https://java2blog.com/fill-array-with-random-numbers-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=fill-array-with-random-numbers-javascript https://java2blog.com/fill-array-with-random-numbers-javascript/#respond Sun, 04 Dec 2022 10:15:19 +0000 https://java2blog.com/?p=21615 Using Array.from() and Math.random() method

To fill array with random numbers in JavaScript:

  • Use Math.random() to get random numbers between 0 to 1.
  • Use array.from() with length with desired length and mapping function as () => Math.random() * 20. This mapping function will be executed for every element in the array.

Let’s say we want to fill an Array with 10 random numbers. Here is the code:

const randomArr = Array.from({length: 10}, () => Math.random() * 20)

console.log(randomArr)

Output:

[
    5.385195687137845,
    4.772307958225093,
    19.64212300782043,
    5.61879993959864,  
    3.537553714391697,
    18.452650370232455,
    11.434937297894695,
    1.421907957295101,
    17.80670020270698,
    1.94687106836811
  ]

Here are the 10 random numbers that we have generated. We set the range to 20, as a result, it filled the array with 10 random numbers 1 between 20.

We multiplied Math.random() by 20, so that we can get random numbers between 1 and 20.

You can round numbers to 2 decimal places in case you need less decimal points.

If you don’t want the floating points, you can simply use the Math.floor() method to avoid them. Here’s the solution to it:

const randomArr = Array.from({length: 10}, () => Math.floor(Math.random() * 20))

console.log(randomArr)

Output:

[
  4, 17, 15, 11,  0,
  1, 16, 17, 16, 18
]

You result may be different from ours because each time it will generate different numbers.

We used array.from() to create an array and used Math.random() to generate random numbers,

array.from() accepts callback function that helps you to execute mapping function for each elements of array.

Here mapping function is () => Math.random() * 20

Using for loop(), array.push(), and Math.random() Method

To fill array with random numbers:

  • Use for loop to iterate over array of desired length.
  • Use Math.random()*20 to generate random numbers between 1 and 20. You can replace 20 with whatever range you are looking for.
  • Use array.push() method to add new elements at the end of the array.

Follow the below program:

let randomArr = [];
for (let i=0, j=10; i

Output:

[
  6, 18, 10, 10, 11,
  4, 15,  1, 19,  2
]

Fill array with unique random numbers

If you notice the output, you may be able to see that there are repeated numbers in the array. What if we want to fill the array with random numbers that are unique? To do so, follow the below code example:

let randomArr = [];
for (let i=0, j=10; i

Output:

[
   8, 19, 11, 12,  2,
   16,  4, 15,  1, 14
 ]

We declared empty array and used for loop to iterate over 10 times.

For each iteration, calculated the random number. If it was already present in the array, we skipped it otherwise we pushed into array using push() method.

That’s all about how to fill array with random numbers.

]]> https://java2blog.com/fill-array-with-random-numbers-javascript/feed/ 0