Common array operations in JavaScript

Programmers, no matter what language they work with always need to work with Arrays. I primarily work with JavaScript and its Dojo library. So here’s a few useful methods to do the common array operations using Dojo/JavaScript:

1. Add an element to the array.

var arr = ["gold", "silver"];
//prints ["gold", "silver", "platinum"]

2. Remove an element from the array.

//pops "platinum"

Adding and removing elements given an element’s index is best done using JavaScript’s splice() method. Look at the next 2 operations below, adding and removing an element.

3. Add an element from the array given its index.

var arr = ["gold", "silver"];
var removed = arr.splice(1, 0, "platinum");
//prints ["gold", "platinum", "silver"] because item "platinum" has been added at index 1.

4. Remove an element from the array given its index.

var arr = ["gold", "silver", "platinium"];

//remove item at index 1 (second argument is 1, which means remove)
var removed = arr.splice(1, 1); 
//prints ["gold", "platinum"] because item "silver" at index 1 has been removed.

Dojo provides some very cool array helper methods as well.

5. Perform an operation on every element of the array.

var arrSalary = [200, 300, 1500, 5, 4500];

// for every element in the array, increment by 10 %.

arrSalary =, function(item) {
            return item + (item / 100) * 10;


//prints [220, 330, 1650, 5.5, 4950] 

6. Filter the contents of an array based on a certain condition

var arrSalary = [200, 300, 1500, 5, 4500];

//filter array elements greater than 300. 
arrSalary = dojo.filter(arrSalary, function(item) {
    return item >=300;


//prints [300, 1500, 4500] 

7. To iterate over an array, dojo provides a easy to use method called dojo.forEach.

dojo.forEach(arr, function(item, i) {
  //do something with each item.

8. Remove duplicates from an array.

var arr = [1,2,3,4,1,6,7,2,7,4];
var newarr = [];
dojo.forEach(arr, function(item, i) {
 if(dojo.indexOf(newarr, item)  == -1) {


These are functions I use on a very regular basis, so I thought I’d write them down and share.