Working with JavaScript arrays

Here's a reference type of post on modify arrays with native JavaScript mathods.

Adding nodes and concatenating Arrays

I’m shamelessly plugging almost the whole “adding” section from a StackOverflow answer by John Strickler, I could not put it better even if I tried. Godspeed to John Strickler, he’s humanitarian and a credit to the society!

Put anything into an array using Array.push().

var a = [],
b = {};
a.push(b);
// a[0] === b;

Add more than one item at a time:

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add items to the beginning of an array:

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Add the contents of one array to another:

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Create a new array from the contents of two arrays:

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

Replace an arbitrary node in array with splice():

var a = [2, 3, 5, 7];
// 1st param: position
// 2nd param: how many to remove
a.splice(2, 1, 'waldo');
console.log(a);
// Result: [2, 3, "waldo", 7]
// Note that the position 2 gets removed

Add an arbitrary node to array with splice():

var a = [2, 3, 5, 7];
a.splice(2, 0, 'waldo');
console.log(a);
// Result: [2, 3, "waldo", 5, 7]
// Note that the position 2 is not removed

Removing nodes from an array

Remove the first item in array:

var a = [2, 3, 5, 7];
a.pop();
console.log(a);
// Result: [2, 3, 5]

Remove the last item in array:

var a = [2, 3, 5, 7];
a.shift();
console.log(a);
// Result: [3, 5, 7]

Remove an arbitrary element in array with splice():

var a = [2, 3, 5, 7];
a.splice(2, 1);
console.log(a);
// Result: [2, 3, 7]

Reverse an array

var a = [2, 3, 5, 7];
a.reverse();
console.log(a);
// Result: [7, 5, 3, 2]

Sorting arrays

Sort an array alphabetically, this is the default behaviour of Array.prototype.sort():

var a = ['d', 'j', 'a', 'b', 'c', 'g'];
a.sort();
console.log(a);
// Result: ["a", "b", "c", "d", "g", "j"]

Sort array in reversed alphabetical order:

// Just reverse the alphabetized array
a.reverse()

Ascending numerical sort:

var a = [5, 7, 3, 2];
a.sort(function(a, b) {
  return a - b;
});
console.log(a);
// Result: [2, 3, 7, 5]

Descending numerical sort, just revert the a and b:

var a = [5, 7, 3, 2];
a.sort(function(a, b) {
  return b - a;
});
console.log(a);
// Result: [2, 3, 7, 5]

Sort by string length:

var a = ['hi', 'hello', 'bonjour', 'moi', 'hola', 'hoi', 'moin'];
a.sort(function(a, b) {
  return a.length - b.length;
});
console.log(a);
// Rsult: ["hi", "moi", "hoi", "hola", "moin", "hello", "bonjour"]

Here’s a little demo for proof:

JS Bin on jsbin.com

Club-Mate, the beverage → club-mate.fi