builtbright GmbH Logo
[Translate to English:]
Tech

JavaScript Snippets: isArray, arguments to Array, [x..y], padding, array.unique()

JavaScript arrays are a powerful data structure, but there are some hidden gems that you might not be aware of. Five useful array methods that can make your code more concise and efficient.January 19, 2012· 4 minutes to read

Now let me post a couple of code snippets that are lying around here already for a while. For the uber geeks out there you might yawn seeing them, but there are a lot of people who are searching for this stuff over and over, including myself. So let me post some small useful snippets that have went through my fingers lately.
Reading on, you will see snippets that help you with 1) detecting if a variable is a real array 2) how to convert it into a proper array 3) how to mimic a x = [3..25] kinda thing that other languages offer 4) how to easily pad a string with leading chararacter (i.e. zeros) and finally 5) how to create a unique function for arrays.

isArray()

There are a lot of ways to check for a variable being an array, but the safest one and also most promoted and secure one is

Object.prototype.toString.call(arg) == '[object Array]';

Some examples from the console demostrate well how to use it and that it really works :)

>>> arr = 1 // That's a simple integer, of course. >>> Object.prototype.toString.call(arr) == '[object Array]'; false >>> arr = '1' // Just a string. >>> Object.prototype.toString.call(arr) == '[object Array]'; false >>> arr = '[1,2,3]' // Also a string. >>> Object.prototype.toString.call(arr) == '[object Array]'; false >>> arr = {x:1, y:2} // That's an object, no array either! >>> Object.prototype.toString.call(arr) == '[object Array]'; false >>> arr = [1,2,3] // An array, so it should be true. >>> Object.prototype.toString.call(arr) == '[object Array]'; true

Convert arguments to an array

One of the pains JavaScript developers have to fight with which will get solved with future versions (fortunately) is that the arguments object looks like an array, e.g. it has the property length but you can’t work with it as if it was an array, e.g. here:

>>> function f() { console.log(arguments.length) } >>> f(1,2,3) 3 // arguments.length works >>> function f() { arguments.slice() } >>> f(1,2) TypeError: arguments.slice is not a function // slice() is not available :(

But their is a workaround until the language handles it. It is

>>> function f() { var realArray = [].slice.call(arguments, 0); console.log(realArray.slice()) } >>> f(1,2,3) [1, 2, 3] // slice throws no error, hurray!

Range function, or mimic “x = [3..25]“

Sometimes you need just a plain array with a set of numbers of a certain range, i.e. when generating a set of chars, like all upper case characters. But there is no “x = [1..5]” in JavaScript yet(!). But I needed one, and it’s easy to make one, as you can see:

>> var chars = []; >>> for (var i=65; chars.push(i) && i<90; i++){}; [65, 66, 67, 68, 69, 70, ... 85, 86, 87, 88, 89, 90] >>> // Let's print them. >>> chars.forEach(function(c){ console.log(String.fromCharCode(c)) }) A ... Z

Padding a string

Sometimes you want to pad numbers with zeros e.g. to align them on the console. Here is how I did that:

>>> ('00' + 3).slice(-3) "003" >>> ('00' + 42).slice(-3) "042" >>> ('00' + 103).slice(-3) "103"

The -3 is the number*-1 of characters my string shall have in the end. I am adding two zeros at the beginning, because I am sure that a number is never an empty string. And after the string concatenation I just take only the last three characters. Simple but works nice without any kind of IFs or complex logic.

array.unique()

PHP has a hell lot of array functions, a bit wild – yeah. But sometimes you wished you had them all too. A unique() function is one of those that I just needed lately again, so here is a simple one:

>>> function unique(arrayData){ return arrayData.filter(function(val, idx, arr){ return arr.slice(0, idx).indexOf(val)==-1 }) } >>> unique([1,2,3,4,1,2,1,3]) [1, 2, 3, 4] >>> unique([1,2,3,4,1,2,1,3,5]) [1, 2, 3, 4, 5] >>> unique(['a', 'a', 'b', 'B']) ["a", "b", "B"]

So have fun, hope something was useful.

Was that helpful for you?
linkShare article
builtbright GmbH Icon
Software, builtbright.

Sustainable web software for SMEs.

Company
keyboard_arrow_down
Resources
keyboard_arrow_down
Follow us
keyboard_arrow_down

© 2024 builtbright GmbH