Post

JavaScript Tips & Tricks

In this post we’ll look at some useful tip and tricks when using JavaScript.

  1. Remove Empty/False Array Elements
  2. JSON Templating
  3. Sorting an Array of Objects
  4. Destructing
  5. Spreading
  6. Create & Submit HTML Form

Remove Empty/False Array Elements

1
2
3
let myArray = ['alex', '', '', 'wells', ''];

myArray.filter(x => x); // ['alex', 'wells']
1
2
3
let myArray = ['alex', '', null, 0, 1, undefined, false, true, [], {}];

myArray.filter(x => x); // ['alex', 1, true, [], {}]


JSON Templating

1
2
3
4
5
6
7
8
let key = 'city';
let value = 'Melbourne';

let obj = {
    [key]: value
};

console.log(obj); // { city: 'Melbourne' }


Remove Duplicates from an Array

Method 1

1
2
3
4
let myArray = [1,2,4,7,2,3,7,4,7,5,3,2,1,1,5,7,8,8,5,3,3,1,6,0,4,0,5,3,1];
let cleanedArray = [...new Set(myArray)];

console.log(cleanedArray); // [ 1, 2, 4, 7, 3, 5, 8, 6, 0 ]

Method 2

  • Array elements will be casted to strings.
  • More code.
  • Better if the Object used to remove duplicates is also required.
1
2
3
4
5
6
7
8
9
10
11
12
13
const removeDuplicates = (arr) => {
    let elements = {};

    arr.forEach(element => {
        elements[element] = true;
    });

    return Object.keys(elements);
}

let myArray = [1,2,4,7,2,3,7,4,7,5,3,2,1,1,5,7,8,8,5,3,3,1,6,0,4,0,5,3,1];

removeDuplicates(myArray); // ['0', '1', '2', '3', '4', '5', '6', '7', '8']


Sorting an Array of Objects

1
2
3
4
5
6
7
8
9
10
// Sort an Array of Objects by a certain key
const sortArrayByKey = (array, keyToSortBy, reverse=false) => {
	if (reverse) {
		// Sort the array in reverse order (Highest to Lowest)
		array.sort((a,b) => a[keyToSortBy] > b[keyToSortBy] ? -1 : 1);
	} else {
		// Sort the array in normal order (Lowest to Highest)
		array.sort((a,b) => a[keyToSortBy] > b[keyToSortBy] ? 1 : -1);
	}
}


Destructing

1
2
3
4
5
6
7
const myFunction = ({name, city, country}) => {
    console.log(name, city, country);
}

let obj = { name: 'Alex', city: 'Melbourne', country: 'Australia' };

myFunction(obj); // Alex Melbourne Australia
1
2
3
4
5
6
7
8
const myFunction = (data) => {
    let { name, city, country } = data;
    console.log(name, city, country);
}

let obj = { name: 'Alex', city: 'Melbourne', country: 'Australia' };

myFunction(obj); // Alex Melbourne Australia


Spreading

Combining Arrays

1
2
3
4
let arrayA = [4, 5, 6];
let arrayB = [1, 2, 3, ...arrayA]; 

arrayB // [1, 2, 3, 4, 5, 6]

Combining Objects

1
2
3
4
5
6
let objA = { name: 'Alex', city: 'Sydney' };
let objB = { ...objA, city: 'Melbourne', country: 'Australia' };
let objC = { city: 'Melbourne', country: 'Australia', ...objA };

console.log(objB); // { name: 'Alex', city: 'Melbourne', country: 'Australia' }
console.log(objC); // { name: 'Alex', city: 'Sydney', country: 'Australia' }

Function Arguments

1
2
3
4
let args = [10, 30, -5, 0, 100];

console.log(Math.min(args)); // NaN
console.log(Math.min(...args)); // -5
1
2
3
4
5
6
7
8
const myFunction = (a,b,c) => {
    console.log(a,b,c);
}

let args = [10, 20, 30];

myFunction(args) // [10, 20, 30] undefined undefined
myFunction(...args); // 10 20 30
1
2
3
4
5
6
7
const myFunction = (a, b, ...c) => {
    console.log(a,b,c);
}

myFunction(10, 20, 30, 40, 50) // 10 20 [30, 40, 50]
myFunction(10, 20) // 10 20 []
myFunction(10) // 10 undefined []


Create & Submit HTML Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const createAndSubmitForm = () => {
	let form = document.createElement('form');
	let formParameter1 = document.createElement('input');

	form.method = 'POST';
	form.action = '/endpoint';

	formParameter1.name='username';
	formParameter1.value='admin';
	form.appendChild(formParameter1);

	document.body.appendChild(form);

	form.submit();
}

createAndSubmitForm();


This post is licensed under CC BY 4.0 by the author.