Site logo

Functions for Array

Sort array

function realSort (x, y) {
	if (x < y) {
		return -1;
	}
	if (x > y) {
		return 1;
	}
	return 0;
}

with (app) {
	var myArray = [14, 52, 3, 14, 45, 36];
	myArray.sort(realSort);
	alert(myArray);
}

Sorting two arrays according to one

Remove duplicates from array

function removeDups (sourceArray)
{
 var tmpArray = new Array;
 var a;
 tmpArray.push (sourceArray.pop().name);
 while (sourceArray.length)
 {
  var nextVal = sourceArray.pop().name;
  for (a=0; a<= tmpArray[a])
   {
    if (nextVal < tmpArray[a])
    {
     tmpArray.splice(a,0, nextVal);
    }
    break;
   }
  }
  if (a == tmpArray.length)
   tmpArray.push (nextVal);
 }
 return tmpArray;
}

Sort array removing duplicates

//~ var array = [12,45,68,79,11,32,11,45,99];
var array = ["Kasyan", "Julia", "Alex", "Kasyan", "Dan", "Patric"];

SortArrayRemovingDuplicates(array);

function SortArrayRemovingDuplicates(array) { 
	var str = array.sort (sortnum).join ('\r')+'\r'; 
	str = str.replace (/([^\r]+\r)(\1)+/g,'$1'); 
	str = str.replace (/\r$/,''); 
	str = str.split ('\r'); 
	return str 
} 

function sortnum (a, b) { 
	return a > b 
}

Get array index

function GetArrayIndex(arr, val) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == val) {
			return i;
		}
	}
	return -1;
}

Array.prototype.contains

Array.prototype.contains = function(obj) {    
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}

Array.prototype.unique

Array.prototype.unique = function() {
var a = this.concat();
for(var i=0; i < a.length; ++i) {
	for(var j=i+1; j < a.length; ++j) {
		if(a[i] === a[j])
			a.splice(j, 1);
	}
}
return a;
};


var array1 = ['a','b','c','d'];
var array2 = ['c','d','e','f'];
var array3 = array1.concat(array2).unique();
alert(array3);

Array.prototype.compare

Array.prototype.compare = function(array) {  
var len = this.length;  
if (len != array.length) return false;  
while (len-->0)  
	 if (this[len] != array[len]) return false;  
  
return true;  
}  
a = [0,100,0,0];  
b = [0,100,0,0];  
a.compare(b)    // true 

See also tips on using arrays