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.๐
Top comments (5)
Better to do
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
Good article. IT helps JavaScript developers to do some array operations in much better way.
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:
and that's something that'll help you with:
Thanks Ben for the heads up,much appreciated!!
Remove falsy values from an array:
Why convert to a Boolean when JS is going to do that anyway? That's the whole point of truey/falsy values