Array from GroupsApp and then indexOf fails [duplicate] - javascript

This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}

members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}

Related

Looping through array of objects in Python coming from Javascript

Coming from Javascript I am trying to learn Python(very slowly). I'm trying to work out how to do a loop in Python script over an array of objects.
For example say I have the following object:
contacts = [{name:"John",age:30},{name:"Peter",age:20},{name:"Sarah",age:33}]
In javascript if I wanted to loop through the array and print to console each name I would do the following.
for (let i = 0; i < contacts.length; ++i) {
console.log(contacts[i][name])
}
Which would print out:
John
Peter
Sarah
Furthermore if I wanted to print the last name in the the list ie Sarah I would do the following
console.log(contacts[contacts.length-1][name])
My question is how would I do this in Python?
contacts = [{"name":"John","age":30},{"name":"Peter","age":20},{"name":"Sarah","age":33}]
for i in range(len(contacts)):
print(contacts[i]["name"])
for person in contacts:
print(person["name"])
The second way would be considered more "Pythonic".
EDIT - added to answer question in comment
To access only the last record in the list, use a negative offset.
print(contacts[-1]["name"])
Try using a for each loop
contacts = [{"name":"John","age":30},{"name":"Peter","age":20},{"name":"Sarah","age":33}]
for contact in contacts:
print(contact["name"])

How to filter array of objects and only return one result without the array brackets [duplicate]

This question already has answers here:
How to find first element of array matching a boolean condition in JavaScript?
(14 answers)
Closed 3 years ago.
I may not have had enough coffee on this lovely monday morning but there's something simple I'd like to do that is not coming to me.
I am filtering on an array of objects for an id:
const skuVariant = skuOptions.filter(sku => sku.itemNumber === variantItemNumber);
This returns an array that is of length 1 if there is a match.
The following line I have:
const skuVariantValueMap = skuVariant && skuVariant[0].varianceValueMap;
I would like to not have to check the for the first element of the array and instead only return the object from the call to filter and not the object inside an array.
To be extra clear skuVariant returns this: [{id: 1234}]
I would like it to return this: { id: 1234 }
This is possible using lodash utils but that's overkill. I am looking for something vanilla.
Is there an ES7, ES6 / super clean way of achieving this?
Thanks in advance.
Use Array.prototype.find instead of filter. It returns the value of the first element in the array that satisfies the provided testing function.

Javascript list contains a string [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
As an example, how would I determine if "component" is in the array below?
["component.part", "random-component", "prefix-component-name", "component"]
Update:
It seems like my use of false positive was misleading. I meant that it would say that component was in there 4 times, when I want to match the string by itself.
ie. It should return false when checking for the presence of "component" in the below array.
["component.part", "random-component", "prefix-component-name"]
Use the Array.find API.
Example:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
For more usage example.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
One way is to use .find() to get the string you want from the Array.
Try using $.inArray() method.
var list=["component.part", "random-component", "prefix-component-name", "component"];
if($.inArray(" component",list) != -1){
console.log("Item found");
}
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
false positives? Array.prototype.indexOf and Array.prototype.includes both use strict equality which makes that impossible here.
IndexOf won't give you false positive. It will give you 3. If you want to find all elements that has "otherstuff componenet" you can loop through your array and check with String.includes()
Here is a beginner friendly solution.
var arr = ["component.part", "random-component",
"prefix-component-name", "component", "asdf"];
console.log(arr.indexOf('component')); // give u 3
for (var i = 0; i < arr.length; i++){
if (arr[i].includes('component')){
console.log(arr[i]);
}
}

Writing a function in two different ways: one way results in a TypeError and the other does not. Why?

I've come across an issue I don't understand what's going on. Here's the setup: the user enters the screen and inputs a last name. I take the last name and search a phone book (the entire phone book has been retrieved when the user enters the screen so it's just sitting there as a big, fat JavaScript array).
Let's assume each element of the phone book object consists of: a last name, first name and phone number. Now, I'll take the last name inputted by the user and loop across the phone book looking for the last names that match. I'll then push each matching element into an array and display that array to the user.
I've written the method to do this in two different ways. In the first way it returns the list of objects. In the second way (my preference), a TypeError is thrown.
Here is the first approach
$scope.getMatchingLastNames = function(){
for(i=0; i<$scope.phoneBook.length; i++){
if($scope.lastName==$scope.phoneBook[i].lastName){
$scope.filteredArray.push($scope.phoneBook[i]);
}
};
The second approach:
$scope.getList = function(){
$scope.filteredArray = getLastNames($scope.lastName,
$scope.phoneBook, $scope.phoneBook.length);
}
Which calls
function getLastNames(lastName, phoneBook, length)
{
var filteredArray = [];
for(var i=0; i<length; i++){
if(lastName==phoneBook[i].lastName){
filteredArray.push(phoneBook[i]);
}
}
return filteredArray;
}
When I run the second approach I'll get an error in Chrome console as follows:
TypeError: Cannot read property 'lastName' of undefined
And the error points to the if condition:
if(lastName==phoneBook[i].lastName)
Can someone explain to me why the second approach is resulting in an error?
Thanks.
Since what you are trying to achieve is to filter a list of results, I suggest you use angularJs filters
I prepared a jsfiddle for you with a simple example:
https://jsfiddle.net/fb0r7z0q/
This is the key line:
<li ng-repeat="entry in phonebook | filter:qname">
qname being your $scope.lastName

Array with numbers 1-20 [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 9 years ago.
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
I did this with the following:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?
Here's a oneliner:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.
Addendum: ES20xx
[...Array(21).keys()].slice(1);
Array.map => See also...
See also this Stackblitz project.
1 Why not? See this SO answer, and this one for a more profound explanation
You could use a simple loop to do what you want;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);

Categories

Resources