Compared lists in google apps script - list

I am trying to compare 2 lists and find elements in list1 that are NOT present in list2.
list1: [01-0161051, 01-0161053, 01-0161057, 01-0161058, 01-0161065, 01-0161067, 01-0161068]
list2: [01-0161051, 01-0161053, 01-0161057, 01-0161058, 01-0161065, 01-0161066]
Elements in list1 but not in list2 are [01-0161067, 01-0161068]
I tried this code but it does not yield expected results:
missing = null,
i = list1.length;
while(i) {
missing = ( ~list1.indexOf(list2[--i]) ) ? missing : list1[i];
}
Any leads would be appreciated.

function findInOneNotInTwo() {
const list1 = ['01-0161051', '01-0161053', '01-0161057', '01-0161058', '01-0161065', '01-0161067', '01-0161068'];
const list2 = ['01-0161051', '01-0161053', '01-0161057', '01-0161058', '01-0161065', '01-0161066'];
let in1notin2 = [];
list1.forEach(s=>{
if(!~list2.indexOf(s)) {
in1notin2.push(s);
}
});
Logger.log(in1notin2.join(', '));
}
Execution log
1:54:09 PM Notice Execution started
1:54:11 PM Info 01-0161067, 01-0161068
1:54:10 PM Notice Execution completed

var list1 = ['01-0161051', '01-0161053', '01-0161057', '01-0161058', '01-0161065', '01-0161067', '01-0161068'];
var list2 = ['01-0161051', '01-0161053', '01-0161057', '01-0161058', '01-0161065', '01-0161066'];
var missing = list1.filter(x => !list2.includes(x));
console.log(missing); // [ '01-0161067', '01-0161068' ]

Related

How to replace this nested loop?

The goal here is to get the text from a website and append it to the lists so I can then create a dataframe out of it. I managed to make this after lots of Google but now I understand its not the most effective way of doing it, been researching list comprehension but wasnt able to get a successful result.
containers = soup.find_all('td', class_=['TableRecords_EvenLine', 'TableRecords_OddLine'])
dateli = []
descli = []
amtli = []
for container in containers:
date = container.select('div[id*=wtDataMov]')
for element1 in date:
seci1 = element1.get_text()
dateli.append(seci1)
description = container.select('div[id*=wtDescricao]')
for element2 in description:
seci2 = element2.get_text()
descli.append(seci2)
amount = container.select('div[id*=wtValorEur]')
for element3 in amount:
seci3 = element3.get_text()
amtli.append(float(price_str(seci3)))
Ideas? Thanks for you time.
If you want it done using list comprehensions, it would look like this
containers = soup.find_all('td', class_=['TableRecords_EvenLine', 'TableRecords_OddLine'])
dateli = []
descli = []
amtli = []
for container in containers:
dateli += [e.get_text() for e in container.select('div[id*=wtDataMov]')]
descli += [e.get_text() for e in container.select('div[id*=wtDescricao]')]
amtli += [float(price_str(e.get_text())) for e in container.select('div[id*=wtValorEur]')]

Define a closure variable in buckle script

I'm trying to convert the following ES6 script to bucklescript and I cannot for the life of me figure out how to create a "closure" in bucklescript
import {Socket, Presence} from "phoenix"
let socket = new Socket("/socket", {
params: {user_id: window.location.search.split("=")[1]}
})
let channel = socket.channel("room:lobby", {})
let presence = new Presence(channel)
function renderOnlineUsers(presence) {
let response = ""
presence.list((id, {metas: [first, ...rest]}) => {
let count = rest.length + 1
response += `<br>${id} (count: ${count})</br>`
})
document.querySelector("main[role=main]").innerHTML = response
}
socket.connect()
presence.onSync(() => renderOnlineUsers(presence))
channel.join()
the part I cant figure out specifically is let response = "" (or var in this case as bucklescript always uses vars):
function renderOnlineUsers(presence) {
let response = ""
presence.list((id, {metas: [first, ...rest]}) => {
let count = rest.length + 1
response += `<br>${id} (count: ${count})</br>`
})
document.querySelector("main[role=main]").innerHTML = response
}
the closest I've gotten so far excludes the result declaration
...
...
let onPresenceSync ev =
let result = "" in
let listFunc = [%raw begin
{|
(id, {metas: [first, ...rest]}) => {
let count = rest.length + 1
result += `${id} (count: ${count})\n`
}
|}
end
] in
let _ =
presence |. listPresence (listFunc) in
[%raw {| console.log(result) |} ]
...
...
compiles to:
function onPresenceSync(ev) {
var listFunc = (
(id, {metas: [first, ...rest]}) => {
let count = rest.length + 1
result += `${id} (count: ${count})\n`
}
);
presence.list(listFunc);
return ( console.log(result) );
}
result is removed as an optimization beacuse it is considered unused. It is generally not a good idea to use raw code that depends on code generated by BuckleScript, as there's quite a few surprises you can encounter in the generated code.
It is also not a great idea to mutate variables considered immutable by the compiler, as it will perform optimizations based on the assumption that the value will never change.
The simplest fix here is to just replace [%raw {| console.log(result) |} ] with Js.log result, but it might be enlightening to see how listFunc could be written in OCaml:
let onPresenceSync ev =
let result = ref "" in
let listFunc = fun [#bs] id item ->
let count = Js.Array.length item##meta in
result := {j|$id (count: $count)\n|j}
in
let _ = presence |. (listPresence listFunc) in
Js.log !result
Note that result is now a ref cell, which is how you specify a mutable variable in OCaml. ref cells are updated using := and the value it contains is retrieved using !. Note also the [#bs] annotation used to specify an uncurried function needed on functions passed to external higher-order functions. And the string interpolation syntax used: {j| ... |j}

How to convert list of list to simple list by removing duplicate values using scala?

I have following list -
List(List(
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))),
List(((groupName,group1),(tagMember,["192.168.20.30"]))),
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20"])))))
I want to convert it to -
List((groupName, group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))
I tried to use .flatten but unable to form desired output.
How do I get above mentioned output using scala??
I had to make some changes to your input to make it valid.
Input List:
val ll = List(List(
List((("groupName","group1"),("tagMember", List("192.168.20.30","192.168.20.20","192.168.20.21")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20"))))
))
Code below works if the group, and tagMember are the same across all the elements in the list
def getUniqueIpsConstantGroupTagMember(inputList: List[List[List[((String, String), (String, List[String]))]]]) = {
// List[((String, String), (String, List[String]))]
val flattenedList = ll.flatten.flatten
if (flattenedList.size > 0) {
val group = flattenedList(0)._1
val tagMember = flattenedList(0)._2._1
val ips = flattenedList flatMap (_._2._2)
((group), (tagMember, ips.distinct))
}
else List()
}
println(getUniqueIpsConstantGroupTagMember(ll))
Output:
((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))
Now, let's assume you could have different groupNames.
Sample input:
val listWithVariableGroups = List(List(
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20","192.168.20.21")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20")))),
List((("groupName","group2"),("tagMember",List("192.168.20.30","192.168.20.10"))))
))
The following code should work.
def getUniqueIpsForMultipleGroups(inputList: List[List[List[((String, String), (String, List[String]))]]]) = {
val flattenedList = inputList.flatten.flatten
// Map[(String, String),List[(String, List[String])]]
val groupedByGroupNameId = flattenedList.groupBy(p => p._1) map {
case (key, value) => (key, ("tagMember", extractUniqueTagIps(value)))
}
groupedByGroupNameId
}
def extractUniqueTagIps(list: List[((String, String), (String, List[String]))]) = {
val ips = list flatMap (_._2._2)
ips.distinct
}
getUniqueIpsForMultipleGroups(listWithVariableGroups).foreach(println)
Output:
((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))
((groupName,group2),(tagMember,List(192.168.20.30, 192.168.20.10)))

How can I get subList of a List in Apex Salesforce?

I have got a list of SObjects having N number of items/sObjects
SObject[] sList = [sobject1, sboject2, sboject3, ........ , sobjectN]
How can I get just 10 items from the begining of the list
Thanks in advance!
After running this code newList contains only first 10 objects from sList.
SObject[] sList = [sobject1, sboject2, sboject3, ... , sobjectN];
List<SObject> newList = new List<SObject>();
for (Integer i = 0; i< 10; i++) {
newList.add(sList[i]);
}
For more info please reffer to List documentation
I also thought of using while and remove method:
SObject[] sList = [object1, object2,...];
if(sList.size() >= 10){
while(sList.size() > 10){
sList.remove(sList.size() - 1);
}
}
System.debug('values: '+sList);

split List<User> in multiple List<User> in c#

I want to split List of user generic List into its small list with each 5 records.
Ex
I have List: u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15.
so must be split into
List1:u1,u2,u3,u4,u5
List2:u6,u7,u8,u9,u10
List3:u11,u12,u13,u14,u15
Any direct method available or need programing logic in c# ?
You can group on the index:
List<List<User>> lists =
list
.Select((u, i) => new { List = i / 5, User = u })
.GroupBy(g => g.List, g => g.User)
.Select(g => g.ToList())
.ToList();
You can also use Range to make a loop and get a part of the list for each iteration:
List<List<User>> lists =
Enumerable.Range(0, (list.Count + 4) / 5)
.Select(n => list.Skip(n * 5).Take(5).ToList())
.ToList();
You can Use Skip(count) and Take(count) methods.
// These are your objects, put here your init code
var list = Enumerable.Range(1, 20).ToList();
var lists = new List<int>[(list.Count + 4) / 5]; // The array of lists you wanted
for (int i = 0; i < lists.Length; i++)
{
lists[i] = list.Skip(i * 5).Take(5).ToList();
}
The (list.Count + 4) / 5 is a method to round UP the division (if I have 6 elements in list, I want two sublists)
If you really need a List of List...
var lists = new List<List<int>>((list.Count + 4) / 5);
for (int i = 0; i < lists.Capacity; i++)
{
lists.Add(list.Skip(i * 5).Take(5).ToList());
}
I think this might be more efficient since you're not doing groupings, orderings and such. This is just a single iteration over the dataset.
var splitList= new List<IEnumerable<User>>();
List<User> currentList = null;
int count = 0;
foreach(var user in users)
{
if (0 == count% 5)
{
currentList = new List<User>(5);
returnValue.Add(currentList);
}
currentList.Add(key);
count++;
}
return returnValue;