DEV Community

talent
talent

Posted on

4 Helpful Javascript Array 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. Check these tricks which can be very helpful!

👉 𝗟𝗲𝘁’𝘀 𝗴𝗲𝘁 𝘀𝘁𝗮𝗿𝘁𝗲𝗱 🧑‍💻

🌶️ 𝗛𝗼𝘄 𝘁𝗼 𝗿𝗲𝗺𝗼𝘃𝗲 𝗳𝗮𝗹𝘀𝘆 𝘃𝗮𝗹𝘂𝗲𝘀 𝗳𝗿𝗼𝗺 𝗮𝗻 𝗮𝗿𝗿𝗮𝘆 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁.
In #javascript falsy values are false, 0, ” ", null, NaN, undefined. Now we can find out how to remove this kind of value from our array. To achieve this, we are going to use the .filter().🚀

🌶️ 𝗛𝗼𝘄 𝘁𝗼 𝗴𝗲𝘁 𝗮 𝗿𝗮𝗻𝗱𝗼𝗺 𝗲𝗹𝗲𝗺𝗲𝗻𝘁 𝗳𝗿𝗼𝗺 𝗮𝗻 𝗮𝗿𝗿𝗮𝘆 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁.
Sometimes we need to select a value from the array randomly. To create it, we can get a random index number according to the array length.🚀

🌶️ 𝗛𝗼𝘄 𝘁𝗼 𝗦𝗵𝘂𝗳𝗳𝗹𝗲 𝗮𝗻 𝗔𝗿𝗿𝗮𝘆 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Shuffling is easy with the sort method. As long as it returns a random number, positive or negative, we can sort it with a random order.🚀

🌶️ 𝗛𝗼𝘄 𝘁𝗼 𝗙𝗶𝗻𝗱 𝘁𝗵𝗲 𝗶𝗻𝘁𝗲𝗿𝘀𝗲𝗰𝘁𝗶𝗼𝗻 𝗼𝗳 𝘁𝘄𝗼 𝗮𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁.
We can use a Set() to ensure that values in the array we are checking are not duplicated, and we will use .filter and .includes methods. As a result, we will get the array with values that were presented in both arrays.🚀

Image description

Top comments (5)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Better to do

[].filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

As the Boolean constructor is called on falsey values and returns false to filter them.

Although the absolutely best way is to not allow falsey values into an array for processing, then no work is needed

Collapse
 
codemaker2015 profile image
Vishnu Sivan

Good article. IT helps JavaScript developers to do some array operations in much better way.

Collapse
 
moopet profile image
Ben Sinclair

Hi, can I suggest that you put your code into a code block rather than using a screenshot? If you paste it in between three-backticks you get something like this:

console.log("Why hello there");
Enter fullscreen mode Exit fullscreen mode

and that's something that'll help you with:

  • searchability on the page with ctrl/cmd+F
  • searchability through something like Google
  • accessibility (screen-reader users currently see your code as "image description" which is the placeholder Markdown uses here)
  • people wanting to copy/paste your code to try it out for themselves
Collapse
 
talenttinaapi profile image
talent

Thanks Ben for the heads up,much appreciated!!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Remove falsy values from an array:

arr.filter(x=>x)
Enter fullscreen mode Exit fullscreen mode

Why convert to a Boolean when JS is going to do that anyway? That's the whole point of truey/falsy values