merging 2 arrays into an array with 2 columns - google-apps-script

I want to merge 2 arrays in the following format.
array1 = [ "a" , "b" , "c"]
array2 = [ 1 , 2 , 3]
merged_array = [ {"a",1} , {"b",2} , {"c",3}]
The goal is to use this as values of 2 columns and rewrite this back to google sheet.
is my format correct and if yes how should i merge the arrays as said above ?
EDIT:
i decided to use this
var output = [];
for(var a = 0; a <= array1.length; a++)
output.push([array1[a],array2[a]]);
how would this compare to map function, performancewise ?

array1 = [ "a" , "b" , "c"]
array2 = [ 1 , 2 , 3]
merged_array = []
for index, value in enumerate(array1): merged_array.append({value,array2[index]})
print (merged_array)
-> [{'a', 1}, {'b', 2}, {'c', 3}]

Merging two arrays into and array of arrays
function myFunk() {
let array1 = ["a", "b", "c"];
let array2 = [1, 2, 3];
let a = array1.map((e,i) => {return [e,array2[i]];})
Logger.log(JSON.stringify(a));
}
Execution log
4:17:09 PM Notice Execution started
4:17:08 PM Info [["a",1],["b",2],["c",3]]
Array.map()

Related

Karate: How to create a json object/map from 2 arrays and merge them?

I am having 2 arrays
array1 = ['a','b']
array2 = [1,2]
I want to merge these 2 arrays and convert them to map like below:
[
{
"firstparam": 'a'
"secondparam": 1
},
{
"firstparam": 'b'
"secondparam": 2
}
]
I am trying this code:
* def map1 = array1
* def map1 = karate.mapWithKey(map1, 'firstparam')
* def map2 = array2
* def map2 = karate.mapWithKey(map2, 'secondparam')
this code is creating map1 & map2. now I want to merge these 2 maps in the above format. how to do it?
basically, i want to send this map to a feature file which is expected 2 parameters.
* def result = karate.call('*.feature', map)
'*.feature' is expecting 2 parameters per call i.e, firstparam & secondparam
Here you go:
* def array1 = ['a', 'b']
* def array2 = [1, 2]
* def array3 = array1.map((x, i) => ({ firstparam: x, secondparam: array2[i] }))
* match array3 == [{ firstparam: 'a', secondparam: 1 }, { firstparam: 'b', secondparam: 2 }]

Can't figure out how to add duplicate count to end of array

I think I'm totally overthinking this but I can't get out of my head. In Google Sheets, I have a list of work orders that look like this:
Work ID Location Start Time Officer Count
123 North 1100
123 North 1100
123 North 1100
222 South 1200
999 North 1400
999 North 1400
333 South 1200
Each work order always has one Officer assigned to it, so I need to count the duplicated work orders and push them to the end of the array under "Officer Count" so it shows how many total Officers needed. For example, 123 would need 3, 222 needs 1, 999 needs 2, and 333 needs 1.
However, the code I have now pops out the right count, just out of order from the original 2D array so I can't push it to the end of the array. Any suggestions?
var rowRange = sheet.getRange(2, 1, 7, 3).getValues();
//Create Work Number array (1D array)
var oneDArr = rowRange.map(function(row){return row[0];});
//Create object to count number of officers to Work Number
var counts = {};
oneDArr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
//Create Array from Object
var array = [];
var array = Object.entries(counts);
//Set Values to correct location
// sheet.getRange(11, 1, array.length, array[0].length).setValues(array);
}
Description
Here is an example script to get the count of work orders and place them in the original array.
Code.gs
function test () {
try {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
let values = sheet.getDataRange().getValues();
values.shift(); // remove the headers
let ids = values.map( row => row[0] );
ids = [...new Set(ids)]; // create an array of unique ids
console.log(ids);
let count = ids.map( id => 0 ); // initialize count to 0
values.forEach( row => { let index = ids.indexOf(row[0]);
count[index]++;
});
console.log(count);
// now let put back into spreadsheet
ids.forEach( (id,i) => { let j = values.findIndex( row => row[0] === id );
values[j][3] = count[i]; } );
console.log(values);
}
catch(err) {
console.log(err);
}
}
Execution log
8:46:20 PM Notice Execution started
8:46:23 PM Info [ 123, 222, 999, 333 ]
8:46:23 PM Info [ 3, 1, 2, 1 ]
8:46:23 PM Info [ [ 123, 'North', 1100, 3 ],
[ 123, 'North', 1100, '' ],
[ 123, 'North', 1100, '' ],
[ 222, 'South', 1200, 1 ],
[ 999, 'North', 1400, 2 ],
[ 999, 'North', 1400, '' ],
[ 333, 'South', 1200, 1 ] ]
8:46:21 PM Notice Execution completed
References
Array.shift()
Array.map()
Set Object
Array.forEach()
Array.indexOf()
Array.findIndex()

Double Nested JSON to DF

I'm unable to make this JSON:
{
“profiles”: {
“1”: {
“id”: “1”,
“property1”: “value1”,
“property2”: “value2”
},
“2”: {
“id”: “2”,
“property1”: “value21”,
“property2”: “value22”
}
}}
To this format
Desired output
Id Property1 Property2
1 Value1 Value2
2 Value21 Value22
I've attempted different approaches, that just result in one col all data.
Can someone please orient me on this?
Based on this example:
data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
pd.DataFrame.from_dict(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
I would suggest something like:
your_json = {<your_json>}
property1 = []
property2 = []
for key, value in your_json.items():
for k, v in value.items():
property1.append(v['property1'])
property2.append(v['property2'])
data = {'property1': property1, 'property2': property2}
tt = pd.DataFrame.from_dict(data)
print(tt)

how to make lua table key in order

my test code:
local jsonc = require "jsonc"
local x = {
a = 1,
b = 2,
c = 3,
d = 4,
e = 5,
}
for k, v in pairs(x) do
print(k,v)
end
print(jsonc.stringify(x))
output:
a 1
c 3
b 2
e 5
d 4
{"a":1,"c":3,"b":2,"e":5,"d":4}
someone help:
from for pairs output, lua store table by key hash order, how can i change it?
i need output: {"a":1,"b":2,"c":3,"d":4,"e":5}
thanks
Lua tables can't preserve the order of their keys. There are two possible solutions.
You can store the keys in a separate array and iterate through that whenever you need to iterate through the table:
local keys = {'a', 'b', 'c', 'd', 'e'}
Or, instead of a hash table, you can use an array of pairs:
local x = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
}

pluck based on common attribute (rails)

I have a table Followership, in which every record has attributes user_id and follower_id.
I can do something like this:
Followership.limit(10).pluck('user_id, follower_id)
But this will give me result like this [[1,A][2,B],[3,C],[4,A],[1,B][2,D]]
I want to convert the above array in such a way that all arrays with same user_ids should be merged in following form [user_id, FOLLOWER_ID(S)]
i.e;
[[1,[A,B]][2,[B,D]],[3,C],[4,A]]
Here user_id = 1 has two followers A,B and user_id = 2 has two followers B,D
How to do this?
As pointed out by Sergio, you could use group_by with the array that you get after pluck, for example:
arr = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'],[2,'D']]
a.group_by(&:first).map { |k, v| [k, v.map(&:last)] }
#=> [[1, ["A", "B"]], [2, ["B", "D"]], [3, ["C"]], [4, ["A"]]]
Another approach
a = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'][2,'D']]
h = Hash.new { |h, k| h[k] = [] }
a.inject(h) { |sum, t| sum[t[0]] << t[1]; sum}.to_a