Javascript - learn the powerful and flexibility of Array type
Overview
Array
is one of the fundamental type that appears in all programming languages and every programmer should master it.
Here's some situations where you will find array helpful:
- You are required to deal with string concatenation, checking or validating user input. In this case, the
Array
type will be very handy. - If your program requires to deal with the data stored in a database, upon loading them out from the database, the record will be in an array.
- You are caching the data in the memory and the data will be used as reference for reporting purposes. This avoids hitting the database over and over during the report generation.
Use cases
Use case 1 - use an array to keep words and then join it
We want to join the words into a string with different separators.
let array1 = [
'helo',
'world'
];
console.log('join with comma:', array1.join());
console.log('join with space:', array1.join(' '));
console.log('join with line feed:', array1.join('\n'));
Use case 2 - compose a path
For composing the file path or directory path, this is useful and convenient. You may change the separator easily during the calls of array2.join()
as shown below.
let array2 = [
'c:',
'myapp',
'data',
];
console.log('data path:', array2.join('\\'));
Use case 3 - compose HTML section
Generating HTML tags at runtime with Array
is very convenient. It will ease you from inserting new line or repositioning the content.
let array3 = [];
array3.push('<div>');
array3.push('helo world');
array3.push('</div>');
console.log(array3.join(''));
let my_data = { name: 'Tester' };
let array4 = [];
array4.push('<div>');
array4.push(`helo ${my_data.name}`);
array4.push('</div>');
console.log(array4.join(''));
This idea works great in the front end JavaScript where you need to generate a section of UI at runtime. As a result, the web server load will reduce tremendously because it has lesser HTML content to generate.
Use case 4 - keeping the keywords
For example, we have a text file that contains the keyword in each line. It will be loaded into the memory upon the program startup. After that, we split the keyword and we will be able to use it in the user input validation process.
// assumes that 'math_operation' contents are loaded from a file.
let math_operation = `ADD
MINUS
MULTIPLY
DIVIDE`;
let array5 = math_operation.split('\n');
console.log('math operator', array5.join());
console.log('operator position', array5.indexOf('DIVIDE'));
Use case 5 - act as domain values
Domain value checking using Array.indexOf()
. The following example ensures that the user input is either new, copy or delete.
let user_input = 'cancel';
if (['new', 'copy', 'delete'].indexOf(user_input) >= 0) {
console.log('user input is valid');
}
else {
console.log('invalid user input');
}
Use case 6 - search an item in an Array
Searching for an item by matching with string input.
let array6 = ['new', 'copy', 'delete'];
let data6 = array6.filter((a) => {
return a == 'copy';
});
console.log(data6);
Searching for a data object by matching the 'id' field in the object.
let array7 = [
{
id: 1,
product: 'Apple'
},
{
id: 2,
product: 'Banana'
},
{
id: 3,
product: 'Orange'
},
];
let data7 = array7.filter((a) => {
return a.id == 2;
});
console.log(data7);
For example, your program query the database and then stores the result in an array (in the memory). Upon the user looks for the full record, you may look for the record in the array and then returns it to the user. This is the simplest form of 'data caching' which helps in reducing the response time and also reducing the database hit. This is helpful in improving the overall processes.
Use case 7 - use Array as a stack or a LIFO (last in first out) list
The Array type already has function for implementing the concept of stack or LIFO list. This can be achieved with push()
and pop()
.
For example:
let array7 = [];
array7.push('A');
array7.push('B');
array7.push('C');
console.log(array7);
console.log(array7.pop());
console.log(array7.pop());
console.log(array7.pop());
The stack concept is still very important for any programmer even though we seldom use stack concept especially we are focusing on the LOB (line of business) application.
One of the user requirement that still using the stack or LIFO concept is related to the inventory control system. The product is sold and deduct from the stock card or bin card in a LIFO order. Meaning that the inventory cost will be taken from the last available stock.
Use case 8 - use Array as queue (FIFO, first in first out)
Another popular concept is FIFO queue which can be achieved with push()
and shift()
.
For example,
let array8 = [];
array8.push('A');
array8.push('B');
array8.push('C');
console.log(array8);
console.log(array8.shift());
console.log(array8.shift());
console.log(array8.shift());
The queue concept is a very important and we can apply this concept in the following situation:
- For a processing queue, a system can have a queue in the main thread to inject new request and multiple Worker threads to process the request parallelly.
- For FIFO costing method in a inventory control system, the product is sold and deduct from the stock card or bin card in a FIFO order. Meaning that the inventory cost will be taken from the first available stock.
Conclusion
The use case of Array does not stop here. You may want to learn more by reviewing the code in Node.js packages, JQuery library or any other JavaScript libraries.
Related posts
- Nodej.js - the Array.sort() performance and how to use custom sorting
- JavaScript - running a list of function with plug-n-play concept
Back to #JAVASCRIPT blog
Back to #blog listing