JavaScript Array Tips And Tricks

Here is some list of Tips and tricks for Javascript Developer , These can help you to increase productivity.

  • How to Remove false values from an Array?
const str = ['a', null, false, 'b', undefined];
const str1 = str.filter(Boolean)
console.log(str1);
//output: (2) ["a", "b"]
  • How to check if all elements in an array pass a condition?
const num = [2,4,5];
const isOdd = num.every(item => item % 2 === 0);
console.log(isOdd);
//output:   false
  • How to check if at least one element in an array pass a condition?
const age = [12,14,11,10,21];
const isThereAnAdult = age.some(item => item > 18);
console.log(isThereAnAdult);
//output:  true
  • Sort Array of Objects
const objectArr = [ 
    { first_name: 'Lazslo', last_name: 'Jamf'     },
    { first_name: 'Pig',    last_name: 'Bodine'   },
    { first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name))
//output: 
1: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
  • Find out the sum, minimum and maximum value
Sum of Array => array.reduce((a,b) => a+b);
Max value in Array ⇒ array.reduce((a,b) => a>b?a:b);
Min value in Array => array.reduce((a,b) => a<b?a:b);
  • sort number array
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
//(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// Output
//(6) [100, 40, 25, 10, 5, 1]
  • create matrix with array fill
const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); 
//output : 
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]