So this answer is not my own, but thanks to Bruce https://plus.google.com/u/0/+BruceMcpherson/posts
He's given me examples of manipulating 1d and 2d arrays in comparison to others.
here's how to create a 1d array of unique values
function uniqueValues() {
var array = [1,2,2,3,4,1];
var u = array.filter( function (v,i,a) {
return a.indexOf(v) === i;
});
Logger.log (u);
}
// results
// [1.0, 2.0, 3.0, 4.0]
// and extend that to extract unique values from a particular column of a 2d arrray
function uniqueValues2D() {
var array = [[1,"a",2,3,4,1],[1,"b",2,3,4,1],[1,"b",2,3,4,1]];
var col = 1;
var u = array.map( function (v) {
return v[col];
})
.filter( function (v,i,a) {
return a.indexOf(v) === i;
});
Logger.log (u);
}
// results
// [a, b]
Part of my question, was that I wanted only to add one value to an array if it wasn't already there, I was currently adding a whole row. But it was unique :)
Again, Bruce came to the rescue with an explanation :
ok, so you want to add something to a second array from a first array if it does not already exist in the second array
function uniqueValuesAdd() {
var values = [[1,"a",2,3,4,1],[1,"b",2,3,4,1],[1,"c",2,3,4,1]];
var archive = ["x","b","y"];
var col = 1;
values.map( function (v) {
return v[col];
})
.filter( function (v,i,a) {
return a.indexOf(v) === i;
})
.forEach (function (v) {
if (archive.indexOf(v) === -1) archive.push(v);
});
Logger.log (archive);
}
// result...
// [x, b, y, a, c]
Finally, in my original code I was using the some()
function and results were unexpected.
Bruce's example and explanation was clear and concise again
.some() is exactly the same type of function as these others. It returns true or false depending on some criteria that you test on each element of the array. returning a true for any element will cause .some() to return true
function someTest(){
var test1 = [1,2,3,4].some ( function (v) {
return v <1;
});
Logger.log(test1);
// will be false and
var test2 =[1,2,3,4].some ( function (v) {
return v === 3;
// will be true
});
Logger.log(test2);
}
He's advised me and I can see some()
might not be the best method to use for my needs.
The uniqueValuesAdd()
& uniqueValues2D()
gave me expected results on a sample of data.
:) So I'm implementing these methods in my final solution.
Not sure if Bruce uses this forum, but full credit to him, just wished to share results. Can post up my edited code if anyone would find it useful, but the examples & explanations below put me right on track.
Cheers