The standard concat() method only puts both arrays together, duplicates as well.
While we could create a function to handle this, it is just as simple to add a method to the Array Object.
Array.concat2();
Code:
<script type="text/javascript">
// Array.concat2()
// array concatenation method for arrays with duplicates.
// From C and S Design www.candsdesign.co.uk.
// define two functions that will become the method
function checkExist(value,arr) {
for (var zz=0; zz<arr.length; zz++) {
if ( arr[zz] == value)
{
return true;
break
// leave function and return true if duplicate exists
}
}
// otherwise return false
return false
}
// concatenate both arrays and check for duplicates
function concat2(testArray,joinArray) {
for (var zz=0; zz<testArray.length; zz++) {
// pass one array value and the array to join it into
if (checkExist(testArray[zz],joinArray) == false) {
// if duplicate is not found push the value onto the join array
joinArray.push(testArray[zz]);
}
}
}
// create our new function as a method for the Array object
Array.prototype.concat2 = concat2;
</script>
How to call the new method
Code:
<script type="text/javascript">
// define and populate two arrays
Names = new Array("Jack","Jill","Hill","Bucket","Pail","Water");
Arr2 = new Array("Bill","Ben","Little Weed","Bucket","Water","Plant Pot","Rabbit");
// pass both arrays to the method
Names.concat2(Arr2,Names)
//document.getElementById('content').innerHTML = Names ;
</script>
Link to demo page Array.Concat2
__________________
Chris. ->> Links are advertising NOT optimising!! <<-
A foolish consistency is the hobgoblin of little minds
Thought for today:- I SEO the only industry where all the cowboys are Indians?
Last edited by chrishirst; 06-18-2007 at 03:47 PM..
|