JavaScript tips and tricks to be a better developer

get_hariharan

Hari Haran😎

Posted on May 7, 2020

JavaScript tips and tricks to be a better developer

These are some of the very basic Javascript methods that will help you get better in Javascript.
Let's straightly jump into coding.. 💥

Fill array with data

var myArray = new Array(10).fill('A');
console.log(myArray); 

//Output
[ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A' ]

Merge Arrays

var bikes = ['TVS', 'BMW', 'Ducati'];
var cars = ['Mercedes', 'Ford', 'Porsche'];
var autoMobiles = [...bikes, ...cars];
console.log(autoMobiles);

//Output
[ 'TVS', 'BMW', 'Ducati', 'Mercedes', 'Ford', 'Porsche' ]

Intersection of arrays

var setA = [5, 10, 4, 7, 1, 3];
var setB = [3, 11, 1, 10, 2, 6];
var duplicatedValues = [...new Set(setA)].filter(x => setB.includes(x));
console.log(duplicatedValues);

//Output
[ 10, 1, 3 ]

Remove falsy values

var mixedArray = [12, 'web development', '', NaN, undefined, 0, true, false];
var whatIsTrue = mixedArray.filter(Boolean);
console.log(whatIsTrue); 

//Output
[ 12, 'web development', true ]

Get random value

var numbers = [];
for (let i = 0; i < 10; i++) {
    numbers.push(i);
}

var random = numbers[Math.floor(Math.random() * numbers.length)];
console.log(random); 

//Output
 4

Reverse an Array

var reversedArray = numbers.reverse();
console.log(reversedArray);

//Output
[ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]

Sum of all values in array

var sumOfAllNumbers = numbers.reduce((x, y) => x + y);
console.log(sumOfAllNumbers);

//Output
45

Remove duplicates from array

var duplicatedArray = ['hello','hello','web developers']
var nonDuplicatedArray = [...new Set(duplicatedArray)];
console.log(nonDuplicatedArray); 

//Output
[ 'hello', 'web developers' ]

Thanks for reading. I hope this gave you an some insights about the JavaScript array methods. Keep following and Stay tuned for more amazing blogs.

💖 💪 🙅 🚩
get_hariharan
Hari Haran😎

Posted on May 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related