Categories
JavaScript JavaScript Basics

More JavaScript Array Tips — Removing Falsy Values, Get Random Array Entry, and Reversing Arrays

Spread the love

JavaScript, like any other programming languages, have many handy tricks that let us write our programs more easily. In this article, we will look at how to do different things that involve arrays, like removing falsy values, getting random values from an array, and reversing arrays.

Removing Falsy Values

In JavaScript, falsy values include 0, empty string, null , undefined , false and NaN . We often run into these values when we’re processing arrays and they may cause errors.

Values like null , undefined , and NaN often are unexpected and it’s easier if we eliminate them from an array before doing anything else to them.

We can do this with a few ways which involve using the filter method that is available to arrays. The filter method takes in a callback function.

The callback function that has 2 parameters, the first one is an array entry and the second one is the index of the array that’s being iterated to by the filter method. The filter method filter let us defined what we want to keep and return a new array with the entries kept according to the boolean expression we return.

Any function that’s defined that takes at least the value and returns a boolean value can be used as the callback function, so one way we can use the filter method to filter out is to use the Boolean factory function, which takes in any object in its first argument and returns true if it’s truthy and false if it’s falsy. If true is returned from the callback function then the item will be kept.

Otherwise, it will discard the value in the array it returns. For example, we can use the Boolean function by passing in straight into the filter method like we do in the following code:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(Boolean);  
console.log(arr);

Then we get the following output from the console.log :

["yellow", 1, true, "orange"]

We can also use the exclamation mark operator twice to coerce truthy values to true and falsy values to false . We just put the exclamation 2 times in front of value to do this, so we can use the operator like in the following code to filter out falsy values:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(a => !!a);  
console.log(arr);

If we run the code above, we should get the same thing as we did before. Likewise, we can pass in a function that returns the value from the Boolean function instead of passing in Boolean function directly to the filter method to make the expression more clear:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(a => Boolean(a));  
console.log(arr);

We should get the same thing as we did before if we run the code above.

Get a Value Randomly from an Array

To get a random value from an array, we can use the Math.random method to get a random index in addition to some other code.

We more code than just calling the Math.random method because it only returns a random number between 0 and 1, which means that it returns a decimal number between 0 and 1, which we don’t want.

This means that it has to be multiplied by our array’s length to get a value between 0 and the length of our array. Then we need call Math.floor on that result to round it down to the nearest integer.

We can use the Math.random method like in the following code:

let arr = ['yellow', 'orange', 'blue', 'purple', 'green'];  
const chosenValue = arr[(Math.floor(Math.random() * (arr.length)))]  
console.log(chosenValue);

The code above generates the index by running Math.random() * (arr.length) , which will range from 0 to the length of the array. Then we round it down with the Math.floor method which takes a number that we want to round down so that we get the number rounded down to the nearest integer since we don’t want non-integer numbers.

Then we can pass that into the brackets to get the index that was generated.

Reversing an Array

We can reverse an array by using the reverse method that comes with JavaScript array objects. It takes no arguments and reverses an array in place. For example, we can use it as in the following code:

let arr = ['yellow', 'orange', 'blue', 'purple', 'green'];  
arr.reverse();  
console.log(arr);

Then we get:

["green", "purple", "blue", "orange", "yellow"]

from the console.log output above. The reverse method works with any primitive objects in addition to objects. For example, if we have:

let arr = [{  
  a: 1  
}, {  
  b: 2  
}, {  
  c: 3  
}];  
arr.reverse();  
console.log(arr);

Then we get back the following output from the console.log :

[  
  {  
    "c": 3  
  },  
  {  
    "b": 2  
  },  
  {  
    "a": 1  
  }  
]

The reverse method also works with any object that has numerical keys. For example, if we have:

let arrLikeObj = {  
  0: 'a',  
  1: 'b',  
  2: 'c',  
  length: 3  
}  
Array.prototype.reverse.call(arrLikeObj);  
console.log(arrLikeObj);

Then we get back the following output from the console.log :

{  
  "0": "c",  
  "1": "b",  
  "2": "a",  
  "length": 3  
}

As long as the object has numerical keys starting from 0 and increments by 1 from there and a length property, the code above will work. We can also use the apply method to do the same thing like in the following code:

let arrLikeObj = {  
  0: 'a',  
  1: 'b',  
  2: 'c',  
  length: 3  
}  
Array.prototype.reverse.apply(arrLikeObj);  
console.log(JSON.stringify(arrLikeObj, (key, value) => value, 2));

Then once again we get back the following output from the console.log :

{  
  "0": "c",  
  "1": "b",  
  "2": "a",  
  "length": 3  
}

Conclusion

In JavaScript, falsy values include 0, empty string, null , undefined , false and NaN . We often run into these values when we’re processing arrays and they may cause errors. Values like null , undefined , and NaN often are unexpected and it’s easier if we eliminate them from an array before doing anything else to them.

We can do this with a few ways which involve using the filter method that are available to arrays.

We can use the Boolean function or applying the exclamation mark twice to convert an object into a boolean value. To reverse an array, we can use call the reverse method on an array to reverse it.

The reverse method also works with any object that has numerical keys starting from 0 and increments by 1 and a length property. We can get a random entry from an array by using Math.random multiplied by the array’s length and Math.floor methods.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.