Useful Array Methods in JavaScript

Introduction

 
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
  1. var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
  2. var maxInNumbers = Math.max.apply(Math, numbers);
  3. 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]
  1. var numbersArray = [] , max = 100;
  2. 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']
  1. const animals = ['squirrel', 'bear', 'deer', 'salmon', 'rat'];

  2. 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]
  1. var spreadableOne = [1, 2, 3, 4,9,10];
  2. var spreadableTwo = [5, 6, 7, 8];
  3. var combined = [...spreadableOne, ...spreadableTwo]; 
Object into a Sub-Array
 
The below code converts the object into a sub-Array
  1. const weather = {  
  2.      rain: 0,  
  3.      temperature: 24,  
  4.      humidity: 33,  
  5. }  
  6. const entries = Object.entries(weather); 
Split the string into an array
 
The below code converts a string into an Array
  1. const newArray = Array.from('hello');
Joining Array values to a string
 
The below code joins an array into a specified string format
  1. var elements = ['Fire', 'Wind', 'Rain'];
  2. console.log(elements.join());
  3. // expected output: Fire,Wind,Rain
  4. console.log(elements.join(''));
  5. // expected output: FireWindRain
  6. console.log(elements.join('-'));
  7. // expected output: Fire-Wind-Rain
Concating 2 Arrays
 
The below code joins 2 Arrays using the Concat operator
  1. var array1 = ['a', 'b', 'c'];

  2. var array2 = ['d', 'e', 'f'];

  3. console.log(array1.concat(array2));

  4. // expected output: Array ["a", "b", "c", "d", "e", "f"]
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"]
  1. const numbers = [2, 3, 4, 5];

  2. 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]
  1. function uniteUnique(arr)   
  2. {  
  3.     var args = Array.from(arguments);  
  4.     var newArr = [];  
  5.     for (var k = 0; k < args.length; k++)  
  6.    {  
  7.         newArr = newArr.concat(args[k]);  
  8.    }  
  9.    for (var i = 0; i < newArr.length; i++)  
  10.   {  
  11.        for (var j = i + 1; j < newArr.length; j++)  
  12.        {  
  13.             if (newArr[i] === newArr[j])  
  14.             {  
  15.                    newArr.splice(j, 1);  
  16.                    i--;  
  17.              }  
  18.        }  
  19.    }  
  20.    return newArr;  
  21. }  
  22.   
  23. 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"]
  1. const aoa= [[1,2,3,"ab"],[4,5,6],[7,8,9,"da"]];
  2. 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
  1. const employees = [
  2.       { id: 101, name: 'john', group: 'tech-lead' },
  3.       { id: 102, name: 'sam', group: 'associate' },
  4.       { id: 103, name: 'danny', group: 'senior associate' },
  5.       { id: 104, name: 'ketty', group: 'senior associate' },
  6.       { id: 105, name: 'mili', group: 'junior' },
  7.       { id: 106, name: 'mouLi', group: 'senior associate' },
  8.       { id: 107, name: 'George', group: 'senior associate' }
  9. ];

  10. 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.
  1. const employees = [
  2.        { id: 101, name: 'john', group: 'tech-lead' },
  3.        { id: 102, name: 'sam', group: 'associate' },
  4.        { id: 103, name: 'danny', group: 'senior associate' },
  5.        { id: 104, name: 'ketty', group: 'senior associate' },
  6.        { id: 105, name: 'mili', group: 'junior' },
  7.        { id: 106, name: 'mouLi', group: 'senior associate' },
  8.        { id: 107, name: 'George', group: 'senior associate' }
  9. ];

  10. 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
  1. const numbers = [1,2,3,4,5,6,7,8,9];  
  2.   
  3. const { evenNumbers, oddNumbers} = numbers.reduce((obj,number) => {  
  4.       if( number % 2 === 0)  
  5.       {  
  6.           obj.evenNumbers.push(number);  
  7.       }  
  8.       else  
  9.       {  
  10.           obj.oddNumbers.push(number);  
  11.       }  
  12.   
  13.       return Object.assign({},obj);  
  14. },{  
  15. evenNumbers : [],  
  16. oddNumbers : []  
  17. });  
  18.   
  19. console.log(evenNumbers); // (4) [2,4,6,8]  
  20. console.log(oddNumbers); // (5) [1,3,5,7,9] 
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
  1. const employees = [  
  2.         { id: 101, name: 'john', group: 'tech-lead' },  
  3.         { id: 102, name: 'sam', group: 'associate' },  
  4.         { id: 103, name: 'danny', group: 'senior associate' },  
  5.         { id: 104, name: 'ketty', group: 'senior associate' },  
  6.         { id: 105, name: 'mili', group: 'junior' },  
  7.         { id: 106, name: 'mouli', group: 'senior associate' },  
  8.         { id: 107, name: 'George', group: 'senior associate' }  
  9. ];  
  10. // In the above example, we need to get the number of employees in each group. At first,
  11. // it looks difficult but you can easily achieve that by using the below code:  
  12.   
  13. const employeesByGroup = employees.reduce((acc, employee) => {  
  14.        acc[employee.group] = acc[employee.group] + 1 || 1;  
  15.        return acc;  
  16. }, {});  
  17.   
  18. console.log(employeesByGroup); // tech-lead: 1, associate: 1, senior associate: 4, junior: 1} 
Current timezone Isostring
 
The below method returns the current timezone Isostring
  1. var now = new Date(); // Thu Jan 16 2020 18:00:37 GMT+0530 (India Standard Time)

  2. var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString()//2020-01-16T18:00:26.392Z

Conclusion

 
I hope these snippets can help everyone with their development. Happy Coding :)