Faqts : Computers : Programming : Languages : JavaScript : Language Core : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 5 people (80%) answered Yes
Recently 4 of 5 people (80%) answered Yes

Entry

How to substract one Array from another Array and get an Array as its result

Apr 15th, 2002 12:25
Jean-Bernard Valentaten, Suban Asif,


Your question is not quite clear, so I'll try to answer both options 
that I see.
1. If you have two arrays and want to substract the values of one array 
from the other, try something like:
for (i = 0; i < firstArray.length, i++)
{
  firstArray[i] -= secondArray[i];
}
2. If have two arrays and want to delete the entries of the second 
array that arre found in the first array, this should do the trick
newArray = new Array();
var counter = 0;
for (i = 0; i < firstArray.length; i++)
{
  if (!isFound(firstArray[i], secondArray)
    newArray[counter++] = firstArray[i];
}
function isFound(value, myArray)
{
  var retVal = false
  for (i = 0; i < myArray.length(); i++)
  {
    if (myArray[i] == value)
      retVal = true;
  }
  return retVal;
}
Note that if you need to do this very often in a page, you'd better 
think about creating your own datastructures (e.g. hash, binary-trees),
since they have a better run- and serachtime.
HTH,
Jean