Javascript. Create multi dimensional array from calculation - javascript

I am trying to create a multi dimensional array based off of the calculations of another 3D array.
Input array is in format [shift, start Num, end num]
I should be clear the "," is just for visual purposes.
I need each value in its own array location i.e. [value1]=location 0,0 [value2]=location 0,1 [value3]=location 0,2 etc.
Example:
aInput looks like this
[0,1,5]
[1,1,3]
[2,1,2]
aOutput should look like this
[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[1,3,1]
[1,3,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]
[2,3,1]
[2,3,2]
[1,3,2]
[3,1,1]
[3,1,2]
[3,2,1]
[3,2,2]
[3,3,1]
[3,3,2]
[etc]
It needs to increase the number of items in the array based on the shift. i.e 0 = shift would be 1 column, shift = 1 would be 2 columns, shift = 3 would be 3 columns, and so on. This is what I have so far, but I can not figure out how to make it calculate for anything with a shift.
var aInput = new Array();
aInput[0] = new Array("0", "1","5");
aInput[1] = new Array("1", "1","3");
aInput[2] = new Array("2", "1","2");
for (var x=0; x < aInput[x].length; x++){
//Calculate out number
if (aInput[x][0] == 0){ // Im sure this should be a loop of some sort, just not sure how to do it
var i=Number(aInput[x][1]);
while (i <= Number(aInput[x][2])){
//Write to output array
aOutput.push(i);
i++;
}
}
}
Thanks in advance for any help, I'm really stumped on this one.

var aInput = new Array();
aInput[0] = new Array("0", "1", "5");
aInput[1] = new Array("1", "1", "3");
aInput[2] = new Array("2", "1", "2");
var input_indexed = [],
elem = []; // elem holds the row to be added to the output
// Get aInput[] into a more useful arrangement
for (var i = 0; i < aInput.length; i++) {
// Save the range of each column
input_indexed[parseInt(aInput[i][0])] = {
start: parseInt(aInput[i][1]),
end: parseInt(aInput[i][2])
};
// Initialize elem with the start value of each column
elem[aInput[i][0]] = parseInt(aInput[i][1]);
}
// Produce the output
aOutput = [];
done = false;
while (!done) {
aOutput.push(elem.slice(0)); // push a copy of elem into result
for (i = elem.length - 1;; i--) { // Increment elements from right to left
if (i == -1) { // We've run out of columns
done = true;
break;
}
elem[i]++; // Increment the current column
if (elem[i] <= input_indexed[i].end) {
// If it doesn't overflow, we're done
break;
}
// When it overflows, return to start value and loop around to next column
elem[i] = input_indexed[i].start;
}
}
FIDDLE

var aOutput = [];
for (var i in aInput) {
var y = parseInt(aInput[i][1])
for (var x = y; x <= parseInt(aInput[i][2]); x++) {
aOutput.push([i, y, x]);
}
}

Related

Loop through table and save its content

I'm reading an Excel file in javascript.
One of the cell has a VLOOKUP formula:
VLOOKUP(C40,D107:F114,3,FALSE) //(searched value, table range, returned value column, exact match)
What it's basically doing is searching for the the value on C40 in a table range of D107 -> F114 (starting point and end point) and returning the value on the 3 column, on this example- column F. FALSE indicates we are looking for an exact match.
I need to extract the table defined on the formula D107:F114 (3 columns (D, E, F), 8 cells (107, 108, 109, etc.)) and save its content in code.
This is what I did- works fine, I am wondering if there is a shorter way to do it:
const formula = sheet.cell('A40').formula()
var splittedFormula = formula.split(/[\s,]+/) //split formula by params -> splittedFormula = [C40, D107:F114, 3, FALSE]
const numOfColumns = splittedFormula[2] //geting the total number of columns by the third param- "returned value column" -> numOfColumns = 3
let numOfCells = splittedFormula[1].split(/[\s:]+/) //get the start point of the table -> numOfCells = [D107, F114]
let startingCell = numOfCells[0].replace(/\D/g, '') //extract the starting cell -> startingCell = 107
let startingColumn = numOfCells[0].replace(/\d+/g, '') //extract the starting column -> startingColumn = D
numOfCells =
numOfCells[1].replace(/\D/g, '') - numOfCells[0].replace(/\D/g, '') + 1 //calculate how many cells on each column by substracting the start point cell from the end point cell (`114 - 107`) -> numOfCells = 8
var table = new Array(numOfColumns) //defining an array of arrays -> table = [3]
let currentCell
//loop through the table in the excel sheet and save it's content each column is an array that store the cells value. table = [3][8]
for (var i = 0; i < numOfColumns; i++) { //numOfColumns=3
table[i] = new Array(numOfCells) //numOfCells=8
currentCell = startingCell
for (var j = 0; j < numOfCells; j++) {
table[i][j] = sheet.cell(startingColumn + currentCell).value()
currentCell = parseFloat(currentCell) + 1 //increment to the next cell i.e. 107 + 1 = 108 etc..
}
startingColumn = String.fromCharCode(startingColumn.charCodeAt() + 1) //increment to the next column i.e. D + 1 = F etc..
}
The first "minimization" (and most important one) is to check if your sheet instance allows to extract a slice (idem the submatrix or table you try to extract).
On a more generic way you can:
skip some lines about extracting the formula (or at least make it clearer)
let formula = 'D107:F114'
let [colStart, rowStart, colEnd, rowEnd] = formula.match(/([A-Z]+)(\d+):([A-Z]+)(\d+)/).slice(1);
//[ colStart='D', rowStart='107', colEnd='F', rowEnd='114' ]
rowStart = parseInt(rowStart);
rowEnd = parseInt(rowEnd);
colStart = colStart.charCodeAt()-65;
colEnd = colEnd.charCodeAt()-65;
note that here, you may have columns like AA or ZZ so you may want to adapt the transformation of colStart and colEnd accordingly
then use map instead of for loop
let table = Array(colEnd-colStart+1).fill(0).map((_, j)=>{
return Array(rowEnd-rowStart+1).fill(0).map((_, i)=>{
let col = colStart + j;
let row = rowStart + i;
return sheet.cell(String.fromCharCode(col+65)+row).value();
})
})
Regarding AA or ZZ, below an algorithm to convert them back and forth to int, but once again probably rely on your library since it would have to parse your string anyway..
let sheet = {
cell(x){return {value(){return x}}}
}
//not used, but enough to handle single letters...
function toColIdx(s){
return s.charCodeAt()-'A'.charCodeAt();
}
function idxToCol(idx){
return String.fromCharCode(idx+'A'.charCodeAt())
}
let base = (function(){
let idxToChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
let charToIdx = idxToChar.reduce((acc, f,i)=>(acc[f] = i+1, acc),{})
//I have checked the identity of idxToCol == idxToCol(toColIdx(idxToCol)) up to 16384
return {
toColIdx(s){
return s.split('')
.reverse()
.reduce((acc,c,i)=>acc+charToIdx[c]*Math.pow(26,i),0);
},
idxToCol(idx){
if(idx==1)return 'A';
let n = Math.ceil(Math.log(idx)/Math.log(26));
s = '';
for(let i = 0; i<n; ++i){
let x = idx % 26;
if(x != 0){
s = idxToChar[x-1] + s;
idx-=x;
idx /= 26;
}else{
s = 'Z' + s;
idx-=26;
idx /= 26;
if(idx==0) return s;
}
}
return s;
}
}
})();
function extract(sheet, formula){
let [colStart, rowStart, colEnd, rowEnd] = formula.match(/([A-Z]+)(\d+):([A-Z]+)(\d+)/).slice(1);
//[ colStart='D', rowStart='107', colEnd='F', rowEnd='114' ]
rowStart = parseInt(rowStart);
rowEnd = parseInt(rowEnd);
colStart = base.toColIdx(colStart)
colEnd = base.toColIdx(colEnd)
return Array(colEnd-colStart+1).fill(0).map((_, j)=>{
return Array(rowEnd-rowStart+1).fill(0).map((_, i)=>{
let col = colStart + j;
let row = rowStart + i;
return sheet.cell(base.idxToCol(col)+row).value();
})
})
}
console.log(JSON.stringify(extract(sheet, 'A107:D114'),null,2))
console.log(JSON.stringify(extract(sheet, 'BZ107:CA114'),null,2))

Manipulate more javascript array based on another array

I've a strange thing to do but I don't know how to start
I start with this vars
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
So to start all the 3 array have the same length and the very first operation is to see if there is a duplicate value in sky array, in this case the 0 is duplicated and only in this case is at the end, but all of time the sky array is sorted. So I've to remove all the duplicate (in this case 0) from sky and remove the corresponding items from base and sum the corresponding items on ite. So if there's duplicate on position 4,5 I've to manipulate this conditions. But let see the new 3 array:
var new_base = [1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var new_sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var new_ite = [139,38,13,15,6,4,6,3,2,1,2,1,1,1];
If you see the new_ite have 139 instead the 64,52,23, that is the sum of 64+52+23, because the first 3 items on sky are the same (0) so I remove two corresponding value from base and sky too and I sum the corresponding value into the new_ite array.
There's a fast way to do that? I thought a for loops but I stuck at the very first for (i = 0; i < sky.length; i++) lol, cuz I've no idea on how to manipulate those 3 array in that way
J
When removing elements from an array during a loop, the trick is to start at the end and move to the front. It makes many things easier.
for( var i = sky.length-1; i>=0; i--) {
if (sky[i] == prev) {
// Remove previous index from base, sky
// See http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript
base.splice(i+1, 1);
sky.splice(i+1, 1);
// Do sum, then remove
ite[i] += ite[i+1];
ite.splice(i+1, 1);
}
prev = sky[i];
}
I won't speak to whether this is the "fastest", but it does work, and it's "fast" in terms of requiring little programmer time to write and understand. (Which is often the most important kind of fast.)
I would suggest this solution where j is used as index for the new arrays, and i for the original arrays:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var new_base = [], new_sky = [], new_ite = [];
var j = -1;
sky.forEach(function (sk, i) {
if (!i || sk !== sky[i-1]) {
new_ite[++j] = 0;
new_base[j] = base[i];
new_sky[j] = sk;
}
new_ite[j] += ite[i];
});
console.log('new_base = ' + new_base);
console.log('new_sky = ' + new_sky);
console.log('new_ite = ' + new_ite);
You can use Array#reduce to create new arrays from the originals according to the rules:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var result = sky.reduce(function(r, n, i) {
var last = r.sky.length - 1;
if(n === r.sky[last]) {
r.ite[last] += ite[i];
} else {
r.base.push(base[i]);
r.sky.push(n);
r.ite.push(ite[i]);
}
return r;
}, { base: [], sky: [], ite: [] });
console.log('new base:', result.base.join(','));
console.log('new sky:', result.sky.join(','));
console.log('new ite:', result.ite.join(','));
atltag's answer is fastest. Please see:
https://repl.it/FBpo/5
Just with a single .reduce() in O(n) time you can do as follows; (I have used array destructuring at the assignment part. One might choose to use three .push()s though)
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330],
sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17],
ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1],
results = sky.reduce((r,c,i) => c === r[1][r[1].length-1] ? (r[2][r[2].length-1] += ite[i],r)
: ([r[0][r[0].length],r[1][r[1].length],r[2][r[2].length]] = [base[i],c,ite[i]],r),[[],[],[]]);
console.log(JSON.stringify(results));

setAttribute() in a multi dimensional array

What I'm trying to figure out is how to give another class to certain div's in a two-dimensional array that has a value of "3" . This is what I tried at first.
numRows are the amount rows in the array.
numSeatsPerRow are the number of array items in every "numRows".
r and t are the positions in the two-dimensional array.
for(var r = 0; r<numRows; r++){
for(var t = 0; t<numSeatsPerRow; t++){
if(myArray[r][t] === 3){
document.getElementsByTagName("div")[r][t].setAttribute("class", "busySpot");
}
}
}
I soon understood that this wouldn't work. I tried to make a formula which could calculate every position as an ordinary array but couldn't make it work. Is there any other way to solve my problem?
In the code below I create a two-dimensional array based on two different inputs
var myArray = new Array(numRows);
for(var i = 0; i <numRows; i++){
myArray[i] = new Array(numSeatsPerRow);
}
In the next piece of code I give all array items the value 1 and then draw a green box for every item.
for(var h = 0; h<numRows; h++){
document.body.appendChild(//efter varje rad sker ett <br> i utskriften
document.createElement("br"));
document.body.appendChild(
document.createElement("br"));
for(var g = 0; g<numSeatsPerRow; g++){
myArray[h][g] = 1
var vSpot = document.createElement("div");
vSpot.className = "vacantSpot";
document.body.appendChild(vSpot);
}
}
What I'm trying to do in the top code is give the random boxes that I talked about another class.
this is how i came up with the random coordinates:
for(var v = 0; v < 15; v++){
var test = true;
while(test){
var x = Math.floor((Math.random() * numSeatsPerRow) + 0 );
var y = Math.floor((Math.random() * numRows) + 0);
if(myArray[x][y] === 1) {
myArray[x][y] = 3;
test = false;
}
}
}
Thanks!

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

How can I remove rows with unique values, keeping rows with duplicate values?

I have a spreadsheet of surveys, in which I need to see how particular users have varied over time. As such, I need to disregard all rows with unique values in a particular column. The data looks like this:
Response Date Response_ID Account_ID Q.1
10/20/2011 12:03:43 PM 23655956 1168161 8
10/20/2011 03:52:57 PM 23660161 1168152 0
10/21/2011 10:55:54 AM 23672903 1166121 7
10/23/2011 04:28:16 PM 23694471 1144756 9
10/25/2011 06:30:52 AM 23732674 1167449 7
10/25/2011 07:52:28 AM 23734597 1087618 5
I've found a way to do so in Excel VBA:
Sub Del_Unique()
Application.ScreenUpdating = False
Columns("B:B").Insert Shift:=xlToRight
Columns("A:A").Copy Destination:=Columns("B:B")
i = Application.CountIf(Range("A:A"), "<>") + 50
If i > 65536 Then i = 65536
Do
If Application.CountIf(Range("B:B"), Range("A" & i)) = 1 Then
Rows(i).Delete
End If
i = i - 1
Loop Until i = 0
Columns("B:B").Delete
Application.ScreenUpdating = True
End Sub
I'd like to do it in Google Spreadsheets with a script that won't have to be changed. Closest I can get is retrieving all duplicate user ids from the range, but can't associate that with the row. That code follows:
function findDuplicatesInSelection() {
var activeRange = SpreadsheetApp.getActiveRange();
var values = activeRange.getValues();
// values that appear at least once
var once = {};
// values that appear at least twice
var twice = {};
// values that appear at least twice, stored in a pretty fashion!
var final = [];
for (var i = 0; i < values.length; i++) {
var inner = values[i];
for (var j = 0; j < inner.length; j++) {
var cell = inner[j];
if (cell == "") continue;
if (once.hasOwnProperty(cell)) {
if (!twice.hasOwnProperty(cell)) {
final.push(cell);
}
twice[cell] = 1;
} else {
once[cell] = 1;
}
}
}
if (final.length == 0) {
Browser.msgBox("No duplicates found");
} else {
Browser.msgBox("Duplicates are: " + final);
}
}
This is maybe not very efficient, but I think it's what you want:
var ar=[1,3,3,5,6,8,6,6];
console.log("Before:");
display(ar);//1 3 3 5 6 8 6 6
var index=[];
var ar2=[];
for(var a=0;a<ar.length;a++)
{
var duplicate=false;
for(var b=0;b<ar.length;b++)
{
if(ar[a]==ar[b]&&a!=b)
{
duplicate=true;
}
}
if(!duplicate)
{
index.push(a);
}
}
for(var a=0;a<index.length;a++)
{
ar[index[a]]=null;
}
for(var a=0;a<ar.length;a++)
{
if(ar[a]!=null)ar2.push(ar[a]);
}
console.log("After:");
display(ar2);//3 3 6 6 6
function display(x)
{
for(var a=0;a<x.length;a++)console.log(x[a]);
}
The fiddle : http://jsfiddle.net/mageek/6AGQ4/
And a shorter version that is as a function :
var ar=[1,3,3,5,6,8,6,6];
function removeUnique(x)
{
var index=[];
var ar2=[];
for(var a=0;a<ar.length;a++)
{
var duplicate=0;
for(var b=0;b<ar.length;b++)if(ar[a]==ar[b]&&a!=b)duplicate=1;
if(!duplicate)index.push(a);
}
for(var a=0;a<index.length;a++)ar[index[a]]=null;
for(var a=0;a<ar.length;a++)if(ar[a]!=null)ar2.push(ar[a]);
return x;
}
ar=removeUnique(ar);
The fiddle : http://jsfiddle.net/mageek/6AGQ4/2
I'd suggest going for something simple.
Create a short script that flags duplicates
Write the formula directly into the cell "=flagDuplicate(C2,C$2:C$10)"
Copy the forumla down the column
Use Spreadsheet's built in QUERY formula to pull the information you need
"=QUERY(A1:E10; "SELECT * WHERE E = TRUE"; 1)"
Here is a simple function to flag duplicates
function flagDuplicate(value, array) {
var duplicateCounter = 0;
for (var i=0; i<array.length; i++){
if (array[i] == value){ // I avoid === in Spreadsheet functions
duplicateCounter++;
}
}
if (duplicateCounter > 1){
return true;
}else{
return false;
}
}
Too many functions on a large table can slow things down. If it becomes a problem, you can always copy and "paste values only" - that will retain the information but remove the functions.
Best of luck.
Note: When I tested this I noticed that can take a while before the spreadsheet recognizes the new custom function (gives error like can't find function FLAGDUPLICATE)
You could also do it using arrays to handle the whole sheet at once :
function removeUnique(){
var col = 2 ; // choose the column you want to check for unique elements
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data=ss.getDataRange().getValues();// get all data
data.sort(function(x,y){
// var xp = Number(x[col]);// use these to sort on numeric values
// var yp = Number(y[col]);
var xp = x[col];// use these for non-numeric values
var yp = y[col];
Logger.log(xp+' '+yp); // just to check the sort is OK
return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col numeric ascending
});
var cc=0;
var newdata = new Array();
for(nn=0;nn<data.length-1;++nn){
if(data[nn+1][col]==data[nn][col]||cc>0){
newdata.push(data[nn]);
++cc;
if(cc>1){cc=0}}
}
ss.getDataRange().clearContent(); // clear the sheet
sh.getRange(1,1,newdata.length,newdata[0].length).setValues(newdata);// paste new values sorted and without unique elements
}
EDIT : here is the version that keeps all duplicates (the working one)
function removeUnique(){
var col = 2 ; // choose the column you want to check for unique elements
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data=ss.getDataRange().getValues();// get all data
data.sort(function(x,y){
// var xp = Number(x[col]);// use these to sort on numeric values
// var yp = Number(y[col]);
var xp = x[col];// use these for non-numeric values
var yp = y[col];
Logger.log(xp+' '+yp); // just to check the sort is OK
return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col numeric ascending
});
var newdata = new Array();
for(nn=0;nn<data.length-1;++nn){
if(data[nn+1][col]==data[nn][col]){
newdata.push(data[nn]);
}
}
if(data[nn-1][col]==data[nn][col]){newdata.push(data[nn])}
ss.getDataRange().clearContent(); // clear the sheet
sh.getRange(1,1,newdata.length,newdata[0].length).setValues(newdata);// paste new values sorted and without unique elements
}

Categories

Resources