Programming Tutorials

Common array methods in JavaScript
Below are some array functions that are commonly required in order to complete Coderbyte challenges. You can view a longer list of JavaScript array functions here.

indexOf

Return the index of a specific element in the array. If the element does not exist in the array, the function returns -1. ``` var arr = [1, 2, 100, 12, -1]; arr.indexOf(100); // 2 arr.indexOf(5); // -1 ```

push and pop

Push elements to the end of the array and delete the last element from an array. ``` var arr = [1, 2, 3, 4]; arr.push(5) // [1, 2, 3, 4, 5] arr.push(6, 7, 8); // [1, 2, 3, 4, 5, 6, 7, 8] arr.pop(); // [1, 2, 3, 4, 5, 6, 7] ```

shift and unshift

Remove the first element from an array and return that element or add an element to the front of an array. ``` var arr = [1, 2, 100, 12, -1]; var first = arr.shift(); // 1 // arr is now => [2, 100, 12, -1] arr.unshift(5000); // arr is now => [5000, 2, 100, 12, -1] ```

reverse

Reverse the elements in an array. ``` var arr = [1, 2, 100, 12, -1]; arr.reverse(); // [-1, 12, 100, 2, 1] ```

sort

Sort the elements in an array based on a compare function. ``` var arr = [1, 2, 100, 12, -1]; // sort in ascending order arr.sort(function(a, b) { return a - b; }); // [-1, 1, 2, 12, 100] // sort in descending order arr.sort(function(a, b) { return b - a; }); // [100, 12, 2, 1, -1] ```

slice

Return a part of the array specified by two numbers, the start and end indices. ``` var arr = [1, 2, 100, 12, -1]; var cutArr = arr.slice(1, 3); // [2, 100] ```
mrdaniel wrote this tutorial on 1/3/16 |
• +
• 11
• -
• Awesome intro to some of the many methods array's have! Another good source is regex methods on arrays. ;)
• +
• 1
• -
• sort() is making sort by the string unicode To sort numbers, or to make customized sorting, It allows using a callback function as a parameter which is working as follwing: ```/* for each two numbers in the array * if function return is positive, sort asc * if function return is negative, sort desc * if function return is zero, don't sort */```
• +
• 0
• -
• I do not understand why this function has to return an ascending order? thanks for the explanation: arr.sort(function(a, b) { return a - b; });
• +
• -2
• -
• Poor explanation of sort
• +
• -3
• -
• Which algorithm does it use to sort an array? `arr.sort(function(a, b) { return a - b; });`