Truncating an Array

Comparison of Slice, Splice and Length used to truncate an array.

HTML

<div id="output"></div>

CSS

#output {font-size: 30px;}

JavaScript

// Comparing Slice, Splice and Length to truncate an array
// (in this case from 4 elements to 2)
// The output shows the elements remaining after truncation and, in
// brackets, the length of the original array after truncation.
//
// For a comparison of the performance of each of these methods see:
// http://jsperf.com/the-fastest-way-to-truncate-an-array

var o = document.getElementById('output'),
    test_array = ['cat','mouse','dog','chicken'],
    temp;

o.innerHTML += 'test_array: ' + test_array + ' (' + test_array.length + ')<br><br>';

// Slice extracts a section of an array, from elements 'start' to 
// 'end minus 1' and returns a new array
test_array = ['cat','mouse','dog','chicken'];
test_array = test_array.slice(0,0);
o.innerHTML += 'test_array.slice(0,2): ' + test_array + ' (' + test_array.length + ')<br>';

// Splice with one parameter removes all elements from 'n' onwards,
// starting at 0, with the removed elements being returned as an array 
test_array = ['cat','mouse','dog','chicken'];
temp = test_array.splice(2);
o.innerHTML += 'test_array.splice(2): ' + test_array + ' (' + test_array.length + ')<br>';

// Altering the length returns the first 'n' elements starting at 0
test_array = ['cat','mouse','dog','chicken'];
test_array.length = 2;
o.innerHTML += 'test_array.length = 2: ' + test_array + ' (' + test_array.length + ')<br>';

// Slice with an end point greater than the original number of elements
test_array = ['cat','mouse','dog','chicken'];
test_array = test_array.slice(0,6);
o.innerHTML += 'test_array.slice(0,6): ' + test_array + ' (' + test_array.length + ')<br>';

// Splice with an end point greater than the original number of elements
test_array = ['cat','mouse','dog','chicken'];
temp = test_array.splice(6);
o.innerHTML += 'test_array.splice(6): ' + test_array + ' (' + test_array.length + ')<br>';

// Altering the length when the new length is greater than the original length
test_array =...