DEV Community

Cover image for 13 useful JavaScript array tips and tricks you should know
Duomly
Duomly

Posted on • Updated on • Originally published at blog.duomly.com

13 useful JavaScript array tips and tricks you should know

This article was originally published at: https://www.blog.duomly.com/13-useful-javascript-array-tips-and-tricks-you-should-know/

An array is one of the most common concepts of Javascript, which gives us a lot of possibilities to work with data stored inside. Taking into consideration that array is one of the most basic topics in Javascript which you learn about at the beginning of your programming path, in this article, I would like to show you a few tricks which you may not know about and which may be very helpful in coding! Let’s get started.

1. Remove duplicates from an array

It’s a very popular interview question about Javascript arrays, how to extract the unique values from Javascript array. Here is a quick and easy solution for this problem, you can use a new Set() for this purpose. And I would like to show you two possible ways to do it, one with .from() method and second with spread operator (…).

var fruits = [banana, apple, orange, watermelon, apple, orange, grape, apple];


// First method
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]
// Second method
var uniqueFruits2 = [new Set(fruits)];
console.log(uniqueFruits2); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]

Easy, right?

2. Replace the specific value in an array

Sometimes it’s necessary to replace a specific value in the array while creating code, and there is a nice short method to do it which you might not know yet. For this, we may use .splice(start, value to remove, valueToAdd) and pass there all three parameters specifying where we want to start modification, how many values we want to change and the new values.

var fruits = [banana, apple, orange, watermelon, apple, orange, grape, apple];
fruits.splice(0, 2, potato, tomato);
console.log(fruits); // returns [“potato”, “tomato”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]

3. Map array without .map()

Probably everyone knows .map() method of arrays, but there is a different solution that may be used to get a similar effect and very clean code as well. We can use .from() method for this purpose.

var friends = [
    { name: John, age: 22 },
    { name: Peter, age: 23 },
    { name: Mark, age: 24 },
    { name: Maria, age: 22 },
    { name: Monica, age: 21 },
    { name: Martha, age: 19 },
]


var friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames); // returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]

4. Empty an array

Do you have an array full of elements but you need to clean it for any purpose, and you don’t want to remove items one by one? It’s very simple to do it in one line of code. To empty an array, you need to set an array’s length to 0, and that’s it!

var fruits = [banana, apple, orange, watermelon, apple, orange, grape, apple];


fruits.length = 0;
console.log(fruits); // returns []

5. Convert array to an object

It happens that we have an array, but for some purpose, we need an object with this data, and the fastest way to convert the array into an object is to use a well-known spread operator (…).

var fruits = [banana, apple, orange, watermelon];
var fruitsObj = { fruits };
console.log(fruitsObj); // returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}

6. Fulfill array with data

There are some situations when we create an array, and we would like to fill it with some data, or we need an array with the same values, and in this case .fill() method comes with an easy and clean solution.

var newArray = new Array(10).fill(1);
console.log(newArray); // returns [“1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”]

7. Merge arrays

Do you know how to merge arrays into one array not using .concat() method? There is a simple way to merge any amount of arrays into one in one line of code. As you probably realized already spread operator (…) is pretty useful while working with arrays and it’s the same in this case.

var fruits = [apple, banana, orange];
var meat = [poultry, beef, fish];
var vegetables = [potato, tomato, cucumber];
var food = [fruits, meat, vegetables];
console.log(food); // [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]

8. Find the intersection of two arrays

It’s also one of the most popular challenges which you can face on any Javascript interview because it shows if you can use array methods and what is your logic. To find the intersection of two arrays, we will use one of the previously shown methods in this article, to make sure that values in the array we are checking are not duplicated and we will use .filter method and .includes method. As a result, we will get the array with values that were presented in both arrays. Check the code:

var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];
var duplicatedValues = [new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]

9. Remove falsy values from an array

At first, let’s defined falsy values. In Javascript, falsy values are false, 0, „”, null, NaN, undefined. Now we can find out how to remove this kind of values from our array. To achieve this, we are going to use the .filter() method.

var mixedArr = [0, blue, “”, NaN, 9, true, undefined, white, false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns [“blue”, 9, true, “white”]

10. Get random value form the array

Sometimes we need to select a value from the array randomly. To create it in an easy, fast, and short way and keep our code clean we can get a random index number according to the array length. Let’s see the code:

var colors = [blue, white, green, navy, pink, purple, orange, yellow, black, brown];
var randomColor = colors[(Math.floor(Math.random() * (colors.length)))]

11. Reversing an array

When we need to flip our array there is no need to create it through the complicated loops and functions, there is an easy array method which does it all for us, and with one line of code, we may have our array reversed. Let’s check it:

var colors = [blue, white, green, navy, pink, purple, orange, yellow, black, brown];
var reversedColors = colors.reverse();
console.log(reversedColors); // returns [“brown”, “black”, “yellow”, “orange”, “purple”, “pink”, “navy”, “green”, “white”, “blue”]

12. .lastIndexOf() method

In Javascript, there is an interesting method which allows finding the index of the last occurrence of the given element. For example, if our array has duplicated values, we can find the position of the last occurrence of it. Let’s see the code example:

var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
var lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9

13. Sum all the values in the array

Another challenge which happens very often during Javascript Engineer interviews. Nothing scary comes here; it can be solved using .reduce method in one line of code. Let’s check out the code:

var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14

Conclusion

In this article, I presented you 13 tricks and tips which can help you with coding and keep your code short and clean. Also, remember there are lots of different tricks which you may use in Javascript worth exploring, not only about arrays but also different data types. I hope you like the solutions provided in the article, and you will use them to improve your development process.

Have a nice coding!


Duomly - programming online courses

Top comments (55)

Collapse
 
mc100s profile image
Maxence Bouret

Thanks for the article :)

Tip 11 (Reversing an array) is also modifying the original array colors.

Instead, if I don't want to change the original array, I would write:

var colors = ["blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"];
var reversedColors = [...colors].reverse();
console.log(reversedColors); // returns ["blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
catalin560 profile image
catalin560

or colors.slice().reverse() works too

Collapse
 
willsmart profile image
willsmart

Tip 10 has an off-by-one error going on: there's no need to add one to colors.length since it's already one more than the highest index.

Great tips though! I didn't know about the array.length = 0 one and will use it for sure.

Collapse
 
duomly profile image
Duomly

Thanks for suggestion

Collapse
 
gabrielpinheiro profile image
Gabriel Pinheiro

Great article!
I love how you mentioned the arr.length = 0;, I've seen obj.arr = []; so many times, messing up references is just a matter of time with the latter.

A nice addition would be to change the 8. Find the intersection of two arrays to do it the other way around as Array.prototype.includes is linear and Set.prototype.has is constant, for larger lists a big difference can be noticed:

let firstValues = [...new Set(numOne)];
let duplicatedValues = numTwo.filter(item => firstValues.has(item));

instead of:

var duplicatedValues = […new Set(numOne)].filter(item => numTwo.includes(item));
Collapse
 
perpetualwar profile image
Srđan Međo

You spread Set into an array, so array won't have has method on it. Small bug on your side.

Collapse
 
gabrielpinheiro profile image
Gabriel Pinheiro

Oh you're right, first line should have been:

let firstValues = new Set(numOne);

Thanks for pointing that up

Collapse
 
andrewbogushevich profile image
Andrew Bogushevich • Edited
numOne = [1, 2]
numTwo = [1, 3, 1]

// original
let duplicatedValues = [new Set(numOne)].filter(item => numTwo.includes(item));
// [1]

// your
let firstValues = new Set(numOne);
duplicatedValues = numTwo.filter(item => firstValues.has(item));
// [1, 1]

to solve this we need either to create second Set or to use includes instead of has

Collapse
 
adamculpepper profile image
Adam Culpepper • Edited

and need to be converted to regular double quotes (") or single quotes so your code can be copy/pasted into the console without having to convert them all.

the character you used for the spread operator (…) needs to be converted to three periods (.) for copy/paste purposes. I think it's also important to note in the article that the spread operator is ES6.

grammar/word errors:
"Get random value form the array" title > needs to be "from array"

Great article, thanks for posting! :)

Collapse
 
moreurgentjest profile image
more-urgent-jest

yes, I totally agree that if you are going to have code in your article make sure that it's valid!!! that's more important than it being pretty. you could use codepen or similar to ensure it actually runs.

Collapse
 
clarity89 profile image
Alex K.

Nice list!

Point 3 is more useful when applied to array-like objects, e.g. NodeList, since you can transform them into arrays and map the items to new values at the same time.

Collapse
 
sakhmedbayev profile image
sakhmedbayev • Edited

Thanks for the post! I need, however, to point out that the solution for finding an intersection array (#8) not quite correct. Try to find an intersection array for these two arrays using your solution:

[1, 1, 1, 2, 1, 3, 4, 2, 2, 2, 2, 2, 2, 2, 2, 4, 5, 6],
[2, 2, 2, 1, 1, 6, 7, 8, 2, 2, 2, 2]

the output is [ 1, 2, 6 ] when actually it supposed to be [ 1, 1, 2, 2, 2, 2, 2, 2, 2, 6 ] (sorted version)

The Set does not work well to find a proper intersection array.

Collapse
 
iamndeleva profile image
iamndeleva

Hello ...i want to learn js can someone share with me a tutorial or course

Collapse
 
hankoj profile image
Jacob Hanko

You will be able to find all different kinds of tutorials out there for JavaScript, ranging from books to video courses. Here are a few to get you started, but I suggest finding a tutorial that complements your own personal learning style.

Collapse
 
iamndeleva profile image
iamndeleva

Thanks

Collapse
 
duomly profile image
Duomly

We have interactive and building real projects courses, you can take a look if you like that (we can give discounts for dev.to) :)

Collapse
 
iamndeleva profile image
iamndeleva

Where are the link for rhe courses

Thread Thread
 
duomly profile image
Duomly

You can find Duomly on duomly.com

Collapse
 
leandrolink profile image
leandrolink

Try freecodecamp.org/ . I really enjoyed that course!

Collapse
 
rahulkumarlal22 profile image
Rahul Kumar Lal
Collapse
 
vijo profile image
vijo

Thanks for the article. Very useful tips in the article as well as the comments!

One query - If i have a two dimensional array (m rows and n columns) - what is the fastest way to create another array with retaining just some selected columns and dropping the others?

Collapse
 
zsivm profile image
zsivm • Edited

Nice post, very useful tips and tricks, thanks. I have found a typo in paragraph 3 in the last part. You wrote: ... user .from() method, instead of use.
In point 9 first row you wrote defined, in point 10 title there is form

Collapse
 
duomly profile image
Duomly

Thanks for pointing, going to fix :)

Collapse
 
zsivm profile image
zsivm

Hi. Sorry for pointing them out individually. I just reached the end. I found another typo in the conclusion, 13 tips and tricks with, instead od which. You are welcome, would like to read from you again :)

Collapse
 
darryl profile image
Darryl Young

Great article. Thanks for sharing.

Collapse
 
alin11 profile image
Ali Nazari

Hi. Great article. I'm willing to translate it into Persian and share it on my blog. I hope you are content :)

Collapse
 
duomly profile image
Duomly

Of course! If you will give link to author duomly.com we are very happy to accept that :)

Collapse
 
alin11 profile image
Ali Nazari • Edited

Thanks. Here is the link. I mentioned you at the bottom of article:

ditty.ir/posts/12-useful-javascrip...

Thread Thread
 
duomly profile image
Duomly

Cool, It's nice we inspired you :)

Collapse
 
nanouchkaya profile image
Claudine

Great article! My favorite trick : array.length = 0 💯

Collapse
 
duomly profile image
Duomly

Thanks Claudine, we are very happy you like our article! :)

Collapse
 
minhpn profile image
MinhPN

Great!

Collapse
 
nithish_13 profile image
Nithish Kumar

Hello everyone,, I want answer for this problem in JavaScript.
const a = 'abcdefghijklmnopqrstuvwxyz'
//Result
['abc','def','ghi',....]
Can someone explain!??
Thanks in Advance 🙂🙂

Collapse
 
flyingduck92 profile image
Sekti Wicaksono

it looks like slicing the output into 3chars-of string

Collapse
 
nithish_13 profile image
Nithish Kumar

S,, finally I did that... ;)

Collapse
 
mnepita profile image
Martin Nepita

Thanks for the article, this is just what I needed !