814Swapping Array Items in Javascript

var myArray = ["a", "c", "b"];
myArray.swap(1, 2);
// ["a", "b", "c"];

Array.prototype.swap=function(a, b) {
    this[a]= this.splice(b, 1, this[a])[0];
    return this;
It could also be done with a temp var, but this solution seems to be the most elegant. The key to this is in the additional arguments the splice() function can accept.
splice(start, itemCount, additionalItems ...)
splice() removes elements denominated by the start and itemCount argument, and – if specified – inserts additional items at the same position. Also important to note is that splice() returns an array. And to turn that array into an item again we need to select it directly with [0].

812jQuery: Getting the element index from a list of identical class elements

Let’s say you have a number of identical class elements:
One Title
Another Title
And you want to get a particular element from this list.
var myArray = $(".myClass");
var thirdElement = myArray[2];
But note, that myArray[2] is the HTML element, not an jQuery object. If you want to access it via jQuery, you’ll have to “arm” it…
var myArray = $(".myClass");
var thirdElement = $(myArray[2]);
// [
Interrating over a jQuery selected list can be done with the each() function:
myArray.each(function(i, element){
	var myElement = myArray[i];
	// this
	// element
myElement, element and this would all hold the same value at each iteration. i is obviously the index counter. It’s also described quite clearly at the jQuery Docs, but I think it’s important enough to reiterate.

813Copying Arrays in Javascript with slice(0)

Using Arrays in Javascript retain their values by references.
var oneArray = ["a", "b", "c"];
var anotherArray = oneArray;
anotherArray[0] = "z";

console.log(oneArray, anotherArray);
// ["z", "b", "c"], ["z", "b", "c"]
Ok, but let’s say you’ll need to make a copy of the array. How do you do that?
var oneArray = ["a", "b", "c"];
var anotherArray = oneArray.slice(0);
anotherArray[0] = "z";

console.log(oneArray, anotherArray);
// ["a", "b", "c"], ["z", "b", "c"]
If you’d really, really want you could also wrap it into a prototype function. Although the code-characters savings are minimal.
Array.prototype.copy = function() {
	return this.slice(0);

var anotherArray = oneArray.slice(0);
var anotherArray = oneArray.copy();
Minimal, but maybe contextually for self-explaining.

804Freezing Objects and Arrays in Javascript

Since the ECMA-262 specifications (aka Javascript 1.8.5 aka ECMAScript 5th Edition) it is possible prevent Objects from accepting any changes to their properties. After applying Object.freeze(myObj) it won’t be possible to change, add or remove properties from myObj. So far so good. As in Javascript Arrays also inherit from Object, I could see not reason, why freezing an array should not work.
var obj = {'a':1, 'b:2'};
Object.isFrozen(obj);       // returns true
obj.a = 10;                 // new assignment has no affect
obj.a;                      // returns 1

var arr = [1, 2];
Object.isFrozen(arr);      // returns true
arr[0] = 10;
arr;                       // returns [10, 2] ... ouch!
It turns out, that it seems to be an implementation bug in Safari (5.1). It’s working in the latest Firefox and Chrome releases. To check whether freezing arrays works in your brower, click the following button: ps. I asked the question first on Stack Overflow: ‘Freezing’ Arrays in Javascript?. Thanks for the constructive answers.

802Objects and Key Array Length in Javascript

With arrays is trivial to get the length, with objects, the situations is slightly different. One approach would be to get all the keys and get the length of that array:
More details at Stackoverflow. This functionality is part of EMCAScript 5 specs.

785Filtering Arrays with ECMAScript 5 and filter()

Suppose you have an array of object:
var array = [ 	{a:13, b:false },
		{a:7, b:true },
		{a:78, b:true } ]		
The old, ECMAScript 3 way of checking for objects, in which b is true would be a simple for-loop:
var results = [];
for (var i=0; i

Ok, that's working, but not very elegant nor concise. Luckily, ECMAScript 5 offers a nicer way:

var results = array.filter( function(item) {
	return item.b;		// if item.b is true

749Javascript, Array and For-Loops

Ok, looping over an array is something that we do all the time, for most of us it has become a second nature.
var myArray = ["a", "b", "c", "z"];

for (int i=0; i

But I recently came across a Javascript loop that puzzled me slightly.

var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ i++]; ) {
Let's have a closer look what's happening here. As a reminder, For-statements have the following structure: for (initiation; condition; increment) { block } In the initiation, variables are initiated; Condition tests this var, and if it returns true, continues another loop; and here's something funny; the increment is left blank. Don't panic, because we are already incrementing i at the condition test. This is equivalent:
var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ i]; i++) {
This, however, is not the same:
var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ ++i]; ) {
i gets incremented before it is used to traverse myArray, therefor resulting in this output:
In nice and simple arrays like in this example, it should not make any difference to test the array length at every time coming around, but a larger ones it might be beneficial. As usual, take care that the array does not contain any falsy objects. And don't loop an object that way. Thanks to the Re-introduction to Javascript https://developer.mozilla.org/en/a_re-introduction_to_javascript for clarifying that issue for me.
Turns out things are not so clear after all. Let's consider the following case: I have an array of numbers, I'd like to get the sum of all numbers in the array. One way to do it:
var myArray = [1,2,3,5,7];
for (var i=0, sum=0; i

So, shouldn't this work too...?
var myArray = [1,2,3,5,7];
for (var i=0, sum=0; sum = myArray[i]; i++) {};
console.log(sum);		// undefined
Apparently not... I am trying to find out why not. This, on the other hand works:
for (var i=0, sum=0; this[i]; sum+=this[i++]){};

682Remove empty array fields in PHP

array_filter WITHOUT a callback function removes ‘false’, ‘null’ and ” fields from an array.

654Find Largest Number in Javascript

Nice way and fast way of finding the largest number in an array.
var arr = [1233, 32, 442];
var largest = Math.max.apply(Math, arr);
http://ejohn.org/blog/fast-javascript-maxmin/ http://stackoverflow.com/questions/1379553/how-might-i-find-the-largest-number-contained-in-a-javascript-array

265Like explode(), only componentsSeparatedByString:

PHP explode(“, ” , “One, Two, Three”); Objective-C NSArray *listItems = [@”One, Two, Three” componentsSeparatedByString:@”, “];