How to remove an element from an array

tl;dr version:

1
myArray.splice(3, 1);

The function above will remove the element at index 3. See docs.


Detailed version:

Let’s say we have a simple array of strings, like this one:

1
var a = ['foo', 'bar', 'baz'];

We just want to remove that ‘bar’ element. How can we do this?

For the principle of least surprise, you could expect Array to have a remove function:

1
2
a.remove('bar');
>>> ['foo', 'baz']

The bad news? JavaScript does not have such a function.

The good news? We can create it!

But, first of all, let’s see how this is done in the standard way:

1
2
3
4
a.splice(1, 1);
>>> ['bar']
a
>>> ['foo', 'baz']

What does this splice function do? Simple: it just removes the element at index 1. The first parameter is, indeed, the index, and the second is the number of elements to remove, starting from that index. This is all you need to know about splice. If you’re curious to see what other cool things splice can do, see the MDN documentation.

But what if I don’t know the index?

Oh well, you can get it. Just use indexOf, this way:

1
2
a.indexOf('bar');
>>> 1

Please note that Internet Explorer 8 and below versions don’t support it (you can use a polyfill, though).


Extending the Array object

This is the function I finally came up with.

1
2
3
4
5
6
7
8
9
10
// Removes an element from an array.
// String value: the value to search and remove.
// return: an array with the removed element; false otherwise.
Array.prototype.remove = function(value) {
var idx = this.indexOf(value);
if (idx != -1) {
    return this.splice(idx, 1); // The second parameter is the number of elements to remove.
}
return false;
}

I know some folks out there don’t feel comfortable with extending Array, because they say Bad Things™ could happen. However, I think that a remove function is just a lot more easy to use and remember than splice, and honestly I don’t see any drawbacks with this approach; especially if we protect the global Array object, somehow. What do you think?

Full example (from the browser’s console, as usual):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var myArray = ['foo', 'bar', 'baz'];
>>> undefined
myArray.length
>>> 3
myArray.remove('bar');
>>> ["bar"]
myArray
>>> ["foo", "baz"]
myArray.remove('baz');
>>> ["baz"]
myArray
>>> ["foo"]
myArray.length
>>> 1
myArray.remove('qux');
>>> false

Awesome! But… why can’t I just use the delete keyword?

Oh, so you’ve heard of that magical JavaScript keyword too, isn’t it? You can do cool things with it, like:

1
2
var a = ['foo', 'bar'];
delete a[1];

And it will Just Work™. By the way it has a flaw: it doesn’t simply remove that element from the array, but it actually replaces it with undefined. Example:

1
2
3
4
5
6
var a = ['foo', 'bar', 'baz'];
>>> undefined
delete a[1];
>>> true
a
>>> ["foo", undefined, "baz"]

Leaving place for undesirable things, like:

1
2
a.length
>>> 3   // it should be 2!

In conclusion, if you don’t care about the drawbacks, you can use the delete keyword; otherwise go with the solution explained above.

How to install Sublime Text 3 on Debian

Sublime Text 3

There are many ways of installing Sublime Text 3 on Linux, and it’s super easy if you are using Debian (or another distribution based on it, such as Linux Mint or Kali Linux).

This little shell script installs Sublime Text 3 on your Linux machine, with no effort at all.

Open up your terminal, then copy and paste:

x64 version

1
2
wget http://c758482.r82.cf2.rackcdn.com/sublime-text_build-3083_amd64.deb
sudo dpkg -i sublime-text_build-3083_amd64.deb

i386 version

1
2
wget http://c758482.r82.cf2.rackcdn.com/sublime-text_build-3083_i386.deb
sudo dpkg -i sublime-text_build-3083_i386.deb

The build 3083 was released on 26 March 2015, and it’s still the latest stable build at time of writing. In case you’re interested in other versions, check out the official site.

How to put online your WampServer

WampServer LogoOn your Windows machine you run an Apache web server with some PHP websites in there. What if you want to show all of them to your friends, or want to be reachable by the whole Internet? This may sound quite difficult to achieve, but actually it’s fairly straightforward to put online a web server: let’s see how.

Publishing your Website on the Internet

First of all, you need to get your WAMP stack up and running on your local host. I’ll assume you already have a web application hosted on your own PC, and that is reachable by just typing this URL in the address bar:

1
http://localhost/    # or http://127.0.0.1

Now you should access to your router web interface. Usually it is reachable by navigating to:

1
http://192.168.1.1

However this may vary, depending on your router model. When in doubt, open the command prompt (cmd), type ipconfig and press enter. You should see something like this:

1
2
3
4
5
6
7
8
C:\>ipconfig

Ethernet adapter Local Area Connection:

  Connection-specific DNS Suffix  . :
  IP Address. . . . . . . . . . . . : 192.168.1.27
  Subnet Mask . . . . . . . . . . . : 255.255.255.0
  Default Gateway . . . . . . . . . : 192.168.1.1

Please take note of the IP address: that’s your private address, which uniquely identifies you in your local network. If you try it in your browser, you should be able to see the public contents of your server.

Port Forwarding

In order to be reached by the world, you should tell your gateway where is your web server. All incoming request on port 80 should be redirected to your own private IP address. Even this process may vary; it really depends on your router. By the way, this is what you basically want to do: forward every request on port 80 to 192.168.1.27 (of course you must use your own IP address). But since the router’s web server already keeps the port 80 busy, here’s what you can do:

  • Move the gateway’s web interface to another port;
  • Move your web server to another port.

I’ll pick the last one, since it’s usually easier to do, and the first option is not always possible. So, let’s change the port: open the httpd.conf and find this row:

1
Listen 80

replace it with:

1
Listen <port number>

for example:

1
Listen 8080

And restart the server. Now go to http://localhost:8080 and check that everything went as expected.

Routing the outside web traffic to your own web server

All respectable routers have an advanced section called IP/Port Forwarding: find yours. If you don’t have this, I’m afraid you cannot be reachable by the outside.

Usually you need to add two separate entries: one for TCP and one for UDP packets. Something like this will do the work:

1
2
3
Private IP     Private Port   Type   Public IP/mask   Public Port
192.168.1.27   8080           TCP    0.0.0.0/0        8080
192.168.1.27   8080           UDP    0.0.0.0/0        8080

Apply the changes and restart your router.

Configuring the server to be reachable by everyone

The last step! Open your httpd.conf and find this line:

1
ServerName localhost:80

Change it to:

1
ServerName <your private IP>:80

Example:

1
ServerName 192.168.1.27:80

Just a quick note: you can jump over the step below. It can be done in an easier way by just clicking on the green WampServer tray icon and choosing “Put Online”.

Also find this line:

1
2
#   onlineoffline tag - don't remove
    Require local

Change it to:

1
2
#   onlineoffline tag - don't remove
    Require all granted

In older versions of Apache, the line would look like:

1
2
3
Order Deny,Allow
Deny from all
Allow from 127.0.0.1

And you need to change it to:

1
2
Order Allow,Deny
Allow from all

Restart your web server. Now just find out what’s your current public IP address and try to go to:

1
http://<public IP address>:<port>/

i.e.:

1
http://13.37.223.21:8080/

It should work now! … Or, at least, it worked for me.

Problems? Thoughts? As always, feel free to leave a comment.

The difference between document.getElementById() and jQuery()

Assuming we have a super simple markup like this:

1
<div id="foo"></div>

We just want to get the reference to the element. In classic JavaScript (vanilla JS) we used to do:

1
var foo = document.getElementById('foo');

And now, in the era of modern web development, we simply do:

1
var foo = $('#foo');

They’re equivalent, but they’re not identical. So what’s the actual difference between the two?

Well, let’s be honest: there’s not just one difference. These two functions will return a completely different object, so you can’t simply replace every getElementById() with $('#foo'). This will break your code.

The main difference is that the jQuery object is just a wrapper around the element.

Let’s see this difference a bit more in detail. Here we play with the console:

1
2
3
4
5
6
7
8
9
document.getElementById('foo')
>>> div#foo
$('#foo')
>>> [div#foo,
     context: document,
     selector: "#foo",
     jquery: "1.10.1",
     constructor: function,
     init: function ]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects… including the div we want! In fact, if you call:

1
2
$('#foo')[0]
>>> div#foo

You get the right div and nothing more, just as you would if you were calling document.getElementById('foo').

Laravel 4 is out!

Laaadies and gentlemen! I’m proud to announce that Laravel 4 has been released today!

I’m really excited about this release because it’s the result of an intensive year of hard work. I truly believe it is the best PHP framework out there. The Laravel Team worked hard to bring out the new Laravel4′s cool features, and I’m sure it will prove to be worth of work!

If you haven’t checked out Laravel yet, please please please do it now! It’s just an incredible framework. I love it because it’s so simple, intuitive, and beautiful I can’t even believe it is developed in PHP. If you are a professional PHP developer, you just can’t know Laravel. Give it a try: you’ll never go back. Guaranteed.