Here are some shortcuts or tricks that might be useful for you in the JavaScript programming language.
1. Removing Duplicates from an Array
const uniqueArray = [...new Set(array)];
Using Set to filter duplicate elements from an array.
Implementation example:
const data = [1,1,2,2,3,4];
const uniqueData = [... new Set(data)];
console.log(uniqueData);
output:
[1, 2, 3, 4]
2. Merging Arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2];
Spread syntax "..." is used to combine multiple arrays into one. if you do console.log, then the output is:
[1,2,3,4,5,6]
3. Searching for Elements in an Array
const array = [1, 2, 3, 4, 5];
const hasNumber = array.includes(3); // true
includes() checks whether an element is present in an array or not. It returns a boolean value.
4. Emptying an Array
let array = [1, 2, 3, 4];
array.length = 0;
Changing length to 0 will delete all elements in the array.
5. Getting the Last Element
const array = [1, 2, 3, 4];
const lastElement = array[array.length - 1]; // 4
Access the last element using array[array.length - 1].
6. Converting Array to Object
const array = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(array); // { a: 1, b: 2 }
Use Object.fromEntries() to convert an array of key-value pairs to an object.
7. Filling an Array with Specific Values
const filledArray = new Array(5).fill(0); // [0, 0, 0, 0, 0]
Array().fill() can be used to create a new array of a certain length and fill it with the same values.
8. Truncate Array (Slicing)
const array = [1, 2, 3, 4, 5];
const slicedArray = array.slice(1, 4); // [2, 3, 4]
slice() returns part of an array without changing the original array.
9. Filtering Elements By Condition
const array = [1, 2, 3, 4, 5];
const evenNumbers = array.filter(num => num % 2 === 0); // [2, 4]
filter() create a new array with elements that satisfy certain conditions.
10. Using Reduce to Add Numbers
const array = [1, 2, 3, 4, 5];
const sum = array.reduce((acc, num) => acc + num, 0); // 15
reduce() can be used to accumulate array values (e.g., summation).
11. Flattening (Converting Nested Arrays Into One Level)
const nestedArray = [1, [2, [3, 4]], 5];
const flatArray = nestedArray.flat(2); // [1, 2, 3, 4, 5]
flat() used to flatten nested arrays to a certain depth. Here 2 means flatten to two levels.
12. Mapping and Flattening at Once (flatMap)
const array = [1, 2, 3]; // Using flatMap const flatMappedArray = array.flatMap(num => [num * 2]); console.log(flatMappedArray); // Output: [2, 4, 6] - All element merged at once
flatMap() perform map() and flat() at once, which is more efficient.
13. Refactor Data Using Maps
const array = [1, 2, 3, 4, 5];
const evenOrOdd = array.map(num => (num % 2 === 0 ? 'even' : 'odd')); // ['odd', 'even', 'odd', 'even', 'odd']
By using the (ternary) condition in map(), we can change the contents of the array.
14. Counting Occurrences of Elements in an Array
const array = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const countOccurrences = array.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); // { apple: 3, banana: 2, orange: 1 }
Using reduce() to count the frequency of each element in an array.
15. Randomizing the Order of Array Elements
const array = [1, 2, 3, 4, 5];
const shuffledArray = array.sort(() => Math.random() - 0.5);
sort() with Math.random() can be used to randomize an array.
16. Finding Minimum and Maximum Values
const array = [5, 1, 8, 3, 7];
const min = Math.min(...array); // 1
const max = Math.max(...array); // 8
Using Math.min() and Math.max() with the spread operator ... to find the minimum and maximum values in an array.
17. Removing Falsy Values from Array
const array = [0, 1, false, 2, '', 3];
const truthyArray = array.filter(Boolean); // [1, 2, 3]
filter(Boolean) removes "falsy" values such as 0, false, null, undefined, NaN, and (empty string).
18. Array with Dynamic Keys
const key = 'fruit';
const array = [{ [key]: 'apple' }, { [key]: 'banana' }];
Create an array with objects that have dynamic keys using the syntax { [key]: value }.
19. Array Destructuring dengan Default Values
const array = [1];
const [a, b = 2, c = 3] = array; // a = 1, b = 2, c = 3
Array destructuring with default values to avoid undefined if the element does not exist.
20. Merge and Delete Elements at Once
const array = [1, 2, 3, 4, 5];
array.splice(1, 2, 'a', 'b'); // array = [1, 'a', 'b', 4, 5]
splice() to delete and add elements in an array at specific positions.
With the shortcuts above, hopefully it will help you more in processing data. Always be happy and keep your smile 😀.