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"];
arr.push("platinum");
//prints ["gold", "silver", "platinum"]

2. Remove an element from the array.

arr.pop();
//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");
console.log(arr);
//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); 
console.log(arr);
//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 = dojo.map(arrSalary, function(item) {
            return item + (item / 100) * 10;
        });

console.log(arrSalary);

//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;
});

console.log(arrSalary);

//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) {
  newarr.push(item);
 }
});

console.log(newarr);

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s