Array Handling Functions

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: Tom, Kukurykus

Andrew

Array Handling Functions

Post by Andrew »

A few simple array handling functions - if you have similar utility functions for arrays or want to suggest improvements on these feel free to post in this thread.

Code: Select all// tests for tString in array1, returns index of match in array1
// csens = case sensitive, clean = remove whitespace before and after text
 
function inArray (tString, array1, csens, clean)
{
   if (clean) tString = tString.replace(/^\s+|\s+$/g,'');
   if (tString.length == 0) return -1;   
   for(var i = 0; i < array1.length; i++) {
      if (clean) array1 = array1.replace(/^\s+|\s+$/g,'');
      if (!csens && array1.toLowerCase() == tString) return i;
      else if (csens && array1 == tString) return i; }
   return -1;   
}

// removes empty array members plus clears whitespaces before and after individual values

function cleanArray (tArray)
{
   var re1 = /^\s+|\s+$/g, nArray = new Array();
   for (var i = 0; i < tArray.length; i++) {
      tArray = tArray.replace(re1,'');
      if (tArray.length > 0) nArray.push(tArray);
   }
   return nArray;   
}

// removes empty members plus whitespaces before and after individual values

function cleanArrayAsString (tArrayStr)
{
   var re1 = /^[,\s]+|[\s,]+$/g;// target space or comma at start or end
   var re2 = /[\s]+,\s+|,\s+|\s+,/g;// target spaces before or /and after commas
   tArrayStr= tArrayStr.replace(re2,',').replace(re1,'');
   tArrayStr = tArrayStr.replace(/,{2,}/g,',');// get rid of multiple commas
   return tArrayStr;   
}
Andrew

Array Handling Functions

Post by Andrew »

A couple more:

Code: Select all// removes entries from array2 already in array1,
// if (csens) makes comparison case sensitive

function remove2ArrayDups (array1,array2, csens)
{
   for(var i = array2.length - 1; i > -1 ; i--) {
      for(var j = array1.length - 1; j > -1 ; j--) {
         if (!csens && array1[j].toLowerCase() == array2.toLowerCase()){
            array2.splice(i,1);break;}
         else if (csens && array1 == array2[j]){
            array2.splice(i,1);break;}
      }
   }
   return array2;   
}

// removes duplicate entries in array1,
// if (csens) makes comparison case sensitive

function remove1ArrayDups (array1, csens)
{
   for(var i = array1.length - 1; i > 0 ; i--) {
      for(var j = i-1;j > -1; j--) {
         if (!csens && array1.toLowerCase() == array1[(j)].toLowerCase()) {
            array1.splice(i,1);break;}
         else if (csens && array1 == array1[(j)]) {
            array1.splice(i,1);break;}
      }      
   }
   return array1;   
}