DEV Community

Hari Haran😎
Hari Haran😎

Posted on • Updated on • Originally published at haricodes.com

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.

Top comments (8)

Collapse
 
get_hariharan profile image
Hari Haran😎

Thank you so much

Collapse
 
mjcoder profile image
Mohammad Javed

Dude, stop spamming. I've seen you post the same message SEVERAL times on another article. It really is annoying. Cut it out, please.

Collapse
 
ender_minyard profile image
ender minyard

lovely.

Collapse
 
get_hariharan profile image
Hari Haran😎

glad you liked it :)

Collapse
 
pris_stratton profile image
pris stratton • Edited

I really like merging arrays with the spread operator. Hadn’t thought of that before.

Collapse
 
abodmicheal profile image
Abod Micheal (he/him)

nice article

Collapse
 
get_hariharan profile image
Hari Haran😎

Thank you so much

Collapse
 
pris_stratton profile image
pris stratton

This has no relevance to my point.