Skip to main content

Command Palette

Search for a command to run...

Javascript Array Methods

Some Useful Javascript Array Methods.

Published
4 min read
Javascript  Array Methods
K

I am a web developer - both front end developer / designer and backend programmer and passionate about new technologies.

Join

Joins array elements using provided separator and returns a string.

var numbers = [1, 2, 3, 4, 5];
var result = numbers.join(',');
console.log(result);
// Output: "1,2,3,4,5"

Reverse

Reverse the order of elements in the array.

var numbers = [1, 2, 3, 4, 5];
var result = numbers.reverse();
console.log(result);
// Output:  [5, 4, 3, 2, 1]

Sort

It Sorts array elements using default sorting.

var numbers = [2, 3, 1, 5, 4];
var result = numbers.sort();
console.log(result);
// Output:  [1, 2, 3, 4, 5]

Concat

Creates and return a new array that contains the concatenation of arrays on which it is invoked.

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var result = arr1.concat(arr2)
console.log(result, arr1);
// Output:  [1, 2, 3, 4, 5, 6], [1, 2, 3]

Slice

Returns a slice(subarray) of the array. but it will not affect the existing array

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.slice(0,2)
console.log(result, arr1);
// Output:  [1, 2], [1, 2, 3, 4, 5]

splice

General purpose method for insertion and removal. It will affect the existing array.

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.splice(0,2)
console.log(result, arr1);
// Output:  [1, 2], [3, 4, 5]

push

Append One more element to the array

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.push(6)
console.log(arr1);
// Output:  [1, 2, 3, 4, 5, 6]

pop

Deletes the last element of the array and returns the element.

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.pop()
console.log(result, arr1);
// Output:  5, [1, 2, 3, 4]

shift

Removes and return first element of array.

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.shift()
console.log(result, arr1);
// Output:  1, [2, 3, 4, 5]

unshift

Add one more element to the beginning of the array, and will return the current length of the array.

var arr1 = [1, 2, 3, 4, 5];
var result = arr1.unshift(7)
console.log(result, arr1);
// Output:  6, [7, 1, 2, 3, 4, 5]

indexOf

* Return the index of a specified element(start from 0) otherwise return -1

var arr1 = [1,2,3,4,5];
var result = arr1.indexOf(4)
console.log(result);
// Output:  3
var result = arr1.indexOf(7)
console.log(result);
// Output:  -1