Skip to content

Instantly share code, notes, and snippets.

@psiborg
Created January 6, 2012 08:23
Show Gist options
  • Select an option

  • Save psiborg/1569669 to your computer and use it in GitHub Desktop.

Select an option

Save psiborg/1569669 to your computer and use it in GitHub Desktop.
JS Arrays
// add items
[1, 2, 3].concat([4, [5, 6]]); // [1, 2, 3, 4, 5, 6]
[1, 2, 3].push([4, [5, 6]]); // [1, 2, 3, 4, [5, 6]]
[1, 2, 3].unshift([4, [5, 6]]); // [4, [5, 6], 1, 2, 3]
// remove items
[1, 2, 3].pop(); // [1, 2]
[1, 2, 3].shift(); // [2, 3]
// extract items
[1, 2, 3, 4, 5].slice(0, 2); // [1, 2]
[1, 2, 3, 4, 5].slice(1, -1); // [2, 3, 4]
[1, 2, 3, 4, 5].slice(-2); // [4,5]
// delete all values after index
[1, 2, 3, 4, 5].splice(2); // [1, 2]
// delete range
[1, 2, 3, 4, 5].splice(2, 2); // [1, 2, 5]
// replace values at deleted range
[1, 2, 3, 4, 5].splice(2, 2, "x", "y", "z"); // [1, 2, "x", "y", "z", 5]
// insert values at index
[1, 2, 3, 4, 5].splice(2, 0, "x", "y", "z"); // [1, 2, "x", "y", "z", 3, 4, 5]
[1, 2, 3].reverse(); // [3, 2, 1]
["a", "A", 9, 80, 700, 6000].sort(); // [6000, 700, 80, 9, "A", "a"]
//----------------------------------------------------------------------------
function numericSort(x, y) {
return x - y;
}
[6000, 80, 700, 9].sort(numericSort); // [9, 80, 700, 6000]
//----------------------------------------------------------------------------
var products = [
{ name: "candy", price: 1.49 },
{ name: "gum", price: 0.79 },
{ name: "mints", price: 1.29 }
];
products.sort(function (x, y) {
return x.price - y.price;
}); // gum, mints, candy
//----------------------------------------------------------------------------
[1, 2, 3].toString(); // "1,2,3"
[1, 2, 3].join(); // "1,2,3"
[1, 2, 3].join("-"); // "1-2-3"
[1, [2, 3]].join("+"); // "1+2,3"
//----------------------------------------------------------------------------
// faster string concatenation for IE
var strArr = [];
for (var i = 0; i < 1000; i++) {
strArr.push("Item " + i);
}
var longStr = strArr.join("\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment