In JavaScript, an array is a special variable that is used to store different elements. It has some built-in properties and methods we can use to add, remove, iterate, or manipulate data following our needs. Knowing JavaScript array methods can lift your skills as a developer.
Array Min Max
The below example shows how to find the minimum and maximum values in an array
- var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
- var maxInNumbers = Math.max.apply(Math, numbers);
- var minInNumbers = Math.min.apply(Math, numbers);
Shortcut for declaring numbers 1-100 in an Array
The below code shortens manual entry of 1-100 in array. It results in numbers = [1,2,3 ,... 100]
- var numbersArray = [] , max = 100;
- for( var i=1; numbersArray.push(i++) < max;);
Remove an array element without mutating the original array
The below code doesn't alter the orginal array and produces the results as mammals that will be equal to ['squirrel', 'bear', 'deer', 'rat']
- const animals = ['squirrel', 'bear', 'deer', 'salmon', 'rat'];
-
- const mammals = [...animals.slice(0,3), ...animals.slice(4)];
Joining 2 Arrays
The below code Joins two arrays and produces the result as combined = [1, 2, 3, 4, 9, 10, 5, 6, 7, 8]
- var spreadableOne = [1, 2, 3, 4,9,10];
- var spreadableTwo = [5, 6, 7, 8];
- var combined = [...spreadableOne, ...spreadableTwo];
Object into a Sub-Array
The below code converts the object into a sub-Array
- const weather = {
- rain: 0,
- temperature: 24,
- humidity: 33,
- }
- const entries = Object.entries(weather);
Split the string into an array
The below code converts a string into an Array
- const newArray = Array.from('hello');
Joining Array values to a string
The below code joins an array into a specified string format
- var elements = ['Fire', 'Wind', 'Rain'];
- console.log(elements.join());
-
- console.log(elements.join(''));
-
- console.log(elements.join('-'));
-
Concating 2 Arrays
The below code joins 2 Arrays using the Concat operator
- var array1 = ['a', 'b', 'c'];
-
- var array2 = ['d', 'e', 'f'];
-
- console.log(array1.concat(array2));
-
-
Merging an Array with an existing element
The below code merges an array with a specified element. The expected result will be ["$2", "$3", "$4", "$5"]
- const numbers = [2, 3, 4, 5];
-
- const dollars = numbers.map( number => '$' + number);
Unique Array
The below code removes the duplicates and provides a unique array. The expected result is [1, 3, 2, 5, 4, 8]
- function uniteUnique(arr)
- {
- var args = Array.from(arguments);
- var newArr = [];
- for (var k = 0; k < args.length; k++)
- {
- newArr = newArr.concat(args[k]);
- }
- for (var i = 0; i < newArr.length; i++)
- {
- for (var j = i + 1; j < newArr.length; j++)
- {
- if (newArr[i] === newArr[j])
- {
- newArr.splice(j, 1);
- i--;
- }
- }
- }
- return newArr;
- }
-
- uniteUnique([1, 3, 2], [5, 2, 1, 4], [8, 1]);
Flattening Array of Arrays
The below code destroys the multiple sub arrays into single array. The expected output is [1, 2, 3, "ab", 4, 5, 6, 7, 8, 9, "da"]
- const aoa= [[1,2,3,"ab"],[4,5,6],[7,8,9,"da"]];
- const flatteredArr = aoa.reduce((acc,arr) => [...acc , ...arr]);
Searching the Array element by value
(Case Insensitive)
The below code searches the value by name, which contains li whether its capitalized or not
- const employees = [
- { id: 101, name: 'john', group: 'tech-lead' },
- { id: 102, name: 'sam', group: 'associate' },
- { id: 103, name: 'danny', group: 'senior associate' },
- { id: 104, name: 'ketty', group: 'senior associate' },
- { id: 105, name: 'mili', group: 'junior' },
- { id: 106, name: 'mouLi', group: 'senior associate' },
- { id: 107, name: 'George', group: 'senior associate' }
- ];
-
- let res = employees.filter(it => new RegExp('li', "i").test(it.name));
(Case Sensitive)
The below code searches the value by name which contains li, strictly case sensitive.
- const employees = [
- { id: 101, name: 'john', group: 'tech-lead' },
- { id: 102, name: 'sam', group: 'associate' },
- { id: 103, name: 'danny', group: 'senior associate' },
- { id: 104, name: 'ketty', group: 'senior associate' },
- { id: 105, name: 'mili', group: 'junior' },
- { id: 106, name: 'mouLi', group: 'senior associate' },
- { id: 107, name: 'George', group: 'senior associate' }
- ];
-
- let res = users.filter(it => it.name.includes('li'));
Splitting Odd and Even numbers
The below code splits the odd and even numbers into separate arrays
- const numbers = [1,2,3,4,5,6,7,8,9];
-
- const { evenNumbers, oddNumbers} = numbers.reduce((obj,number) => {
- if( number % 2 === 0)
- {
- obj.evenNumbers.push(number);
- }
- else
- {
- obj.oddNumbers.push(number);
- }
-
- return Object.assign({},obj);
- },{
- evenNumbers : [],
- oddNumbers : []
- });
-
- console.log(evenNumbers);
- console.log(oddNumbers);
Grouping the Array count
The below code get the number of employees in each group, expected output tech-lead: 1, associate: 1, senior associate: 4, junior: 1
- const employees = [
- { id: 101, name: 'john', group: 'tech-lead' },
- { id: 102, name: 'sam', group: 'associate' },
- { id: 103, name: 'danny', group: 'senior associate' },
- { id: 104, name: 'ketty', group: 'senior associate' },
- { id: 105, name: 'mili', group: 'junior' },
- { id: 106, name: 'mouli', group: 'senior associate' },
- { id: 107, name: 'George', group: 'senior associate' }
- ];
-
-
- const employeesByGroup = employees.reduce((acc, employee) => {
- acc[employee.group] = acc[employee.group] + 1 || 1;
- return acc;
- }, {});
-
- console.log(employeesByGroup);
Current timezone Isostring
The below method returns the current timezone Isostring
- var now = new Date();
-
- var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString()
Conclusion
I hope these snippets can help everyone with their development. Happy Coding :)