Welcome to ciysys blog

Javascript Array use case

Published on: 1st Apr 2024

Overview

Array is one of the fundamental types that appears in all programming languages which every programmer should master.

Here's some situations where you will find array helpful:

Use case 1

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

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('\\'));
console.log('my path format:', array2.join(':'));

Use case 3

Generating HTML tags at runtime with Array is very convenient. It will ease you from adding new lines 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(''));

Use case 4

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 splitted the keyword and it is ready to validate theuser input.

// 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

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

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);

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.

Jump to #JAVASCRIPT blog

Author

Lau Hon Wan, software developer.