Check if element exists in array if not print not found - javascript

I am new to JS. I have task:
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.
Note: Your phone book should be a Dictionary/Map/HashMap data structure.
Input Format
The first line contains an integer, , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number.
After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English alphabetic letters and are first names only.
Here is my code. But i cant check name exists in array or not. Js includes didnt work?
function processData(input) {
//Enter your code here
const n = parseInt(input);
const d = [];
for (var i = 1; i <= n; i++){
var line = input.split('\n').splice(i,1);
let x = line[0].split(" ");
d[x[0]] = x[1];
}
console.log(d)
let m = n;
while (true){
try{
name = input.split('\n').splice(m+1,1);
if ( d.includes(name)){
console.log(name,'=',d[name])
} else console.log('Not found')
m +=1;
}
catch(err){
break
}
}
}

name is the result of a splice on an array, which means it's an array, but you've filled d with strings, so d.includes(name) is looking for a newly-created array inside an array of strings. No array is ever equal to a string (without conversion, which includes doesn't do).
If you meant name to be the entry you removed from the array with splice (since it returns an array of removed entries), you'd need to use [0] on the end to get it:
name = input.split('\n').splice(m+1,1)[0];
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^
I haven't gone through the code to look for other issues, but that will at least look for a string in the array of strings rather than looking for an array in the array of strings.
Side note: You appear to be relying on getting an error to stop your loop, but beware that accessing beyond the end of an array is not an error in JavaScript, you just get the value undefined.

Related

Split and reformat strings from array, check if string starts with certain characters, add missing characters, map result to new arrays

I have an array of usernames + IDs (IDs start with an <#), that I'd like to perform multiple operations on in the same function.
Namely:
Split the strings based on the "|" separator.
check if each string starts and ends with < and > respectively. If not, we will add these back to the string (to restore any missing from a split.)
Output the results to two different arrays, usernames and userIDs
I have the split part working fine, e.g. our current output from the below would be:
<#u01d01m666e,banana050>,<#u01bgh5hads,apple060>
as String.startswith() is unavailable for Arrays, what's the best method to approach this? Should each operation be a separate function, or is it feasible to complete all tasks under one function?
The desired output in this case would be:
a return value of two arrays:
Array #1 contains the UserIDs, in this case:
<#u01d01m666e>,<#u01bgh5hads>,
Array #2 contains the usernames, in this case:
<banana050>,<apple060>
var usernames = ['<#u01d01m666e|banana050>', '<#u01bgh5hads|apple060>'];
var userIDs = usernames.map(function mapper(value, index, array) {
if (typeof value == "string") {
return value.split("|");
} else {
return value.map(mapper);
console.log("The array mapper was given an incorrect input (not a string.)");
}
});
document.getElementById("demo").innerHTML = userIDs;
<!DOCTYPE html>
<html>
<body>
<h1 id="demo"></h1>
</body>
</html>

Finding DOM Values using eq([i])

I have the below code to get all the "Names" given in an IE form, one after the other using javascript. This script suppose to use the IE DOM explorer to get the value.
There would be one or more values that would match the query below at any given time. Therefore, I'll have to use a "For Loop" to get and assign the value to a variable one after the other. I would like to find the maximum number of occurrence to use in the For loop, by getting the value from $('tr.background-light:last').text(). This will contain a number and a name. I am stripping the number only by splitting it cnt=cnt.split(".",1) and assigning this to a variable.
Then using that as my maximum number to loop and trying to assign the value to an array. But it isn't running.
javascript:(function()
{
ver item;
var cnt=$('tr.background-light:last').text(); //getting the last background-light value which will contain the total number of Affected Client's
cnt=cnt.split(".",1); // Stripping just the number out from the above variable
for (var i =0; i <cnt.length; i++)
{
item= $("tr.background-light:eq("+i+")").text(); //looping through to get each affected client info
alert(item)
};
})();

Javascript equivalent of VBS redim preserve

I'm trying to rewrite some old VBScript as Javascript for an ASP.NET application and there is one line I'm not sure how to translate, and I'm not even entirely positive what it's doing.
The application essentially allows the user to enter in a new employee number to add to the database and then assign it user permissions. Don't ask me why the code is such a mess, I didn't write it originally, I'm just trying to make it work in Chrome
here's the relevant code that i've managed to translate so far:
if(form1.txtEmpno.value != ""){
var oOption;
oOption = document.createElement("OPTION");
oOption.text=form1.txtEmpno.value;
oOption.value=form1.txtEmpno.value;
form1.lstActive.add (oOption);
oOption = document.createElement("OPTION");
oOption.text="";
oOption.value="";
form1.lstPerms.add (oOption);
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value;
arrUsers(1,ubound(arrUsers,2)) = "";
form1.txtEmpno.value = "";
oOption = null;
}
here's the line in question:
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
MSDN defines ReDim [Preserve] varname(subscripts) as:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.
Arrays in JavaScript have different semantics to VBScript's arrays, especially in that they're actually closer to a vector than a true array, furthermore JavaScript does not provide for true N-dimensional arrays: instead you use staggered-arrays (arrays-within-arrays). Which means your VBScript cannot be syntactically converted to JavaScript.
Here's your relevant code in VBScript:
ReDim Preserve arrUsers(1,ubound(arrUsers,2)+1)
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value
arrUsers(1,ubound(arrUsers,2)) = ""
We see that arrUsers is a 2-dimensional array. This will need to be converted into a staggered array, but you haven't posted the code that defines and initializes arrUsers, nor how it is used later on, so I can only work from making assumptions.
It looks to be adding 1 element to the last dimension, but the code only seems to use the extra space in the [1] subscript (i.e. it only wants the extra dimensional space for certain values of the 0th dimension instead of all values), which makes this simpler as you don't need to iterate over every 0th-dimension subscript.
JavaScript arrays have numerous function-properties that we'll use, in particular push: which appends an element to the end of an array (internally growing the buffer if necessary), and pop which removes the last (highest-indexed) element from an array (if an array is empty, it's a NOOP):
var arrUsers = [ [], [] ]; // empty, staggered 2-dimensional array
...
arrUsers[0].push( form1.txtEmpno.value );
arrUsers[1].pop();
Much simpler.
However, if this array is just part of some internal model to store and represent data then you should take advantage of JavaScript object-prototypes instead of using array indexes, as that makes the code self-describing, for example:
var User = function(empNo, name) {
this.employeeNumber = empNo;
this.name = name;
};
var users = [];
users.push( new User(1, "user 1") );
users.push( new User(23, "user 23") );
...
for(var i = 0; i < users.length; i++ ) {
alert( users[i].name );
}

How are items being added to this javascript array here?

Looking at a beginner's javascript book and trying to understand a small browser program that builds a list with user input. The input box displays and enters strings as input until he just adds " " as an input. Then the list is shown in the browser.
Here's the code:
var userInput = " ";
var namesArray = new Array();
while ( (userInput = prompt("Enter name", " ")) != " ") {
namesArray[namesArray.length] = userInput;
}
namesArray.sort();
var namesList = namesArray.join("<br />");
var listHolder = document.createElement('div');
var list = listHolder.innerHTML = namesList;
document.body.appendChild(listHolder);
I just don't have understanding of the way the author adds items to the array. Would someone care to explain how namesArray[namesArray.length] = userInput builds an array?
Also here's a fiddle to try it out
Thansk in advance!
So what happens is that, we get a while loop that is going to keep asking for a name until we get an empty response:
while ( (userInput = prompt("Enter name", " ")) != " ")
It then uses the length of the inital namesArray to index the new value.
namesArray[namesArray.length] = userInput;
So we know that the array is initially empty. So on the first run the length is going to be zero! We also know that an index of 0 is the first item in an array. So it adds it to the array as the first item. After that, the array now has a length of 1 (since we just added an item). So on the next iteration we add the new item to the array at the index of 1, which increases its length to 2. This goes on forver until we break the while loop.
So if we break it down we'll see it more clearly:
//First iteration
newArray.length = 0;
newArray[newArray.length] = newArray[0]
//Second iteration
newArray.length = 1;
newArray[newArray.length] = newArray[0]
etc.
Basically .length is the size of the array so .length is the next index of the array without anything in it yet. He just adds the string to the end of the array .length which creates a new position at the end of the array. .length - 1 is the last element of the array so .length would create a new position at the end of the array. The next time through the loop the length will be one greater than the previous time because you added an element to the array.
The condition for the while loop (userInput = prompt("Enter name", " ")) != " ") will remain true as long as a name is entered each time.
Each time a name is entered, the length index is assigned the name. Each time a name is assigned, the length increases. As a result, the array will grow for each name entered.
Normally you could easily add an element to an array via the .push() method. For example:
var ary = []; // empty array
ary.push('foo'); // the ary array now has one element, 'foo'
Now array indices are zero-based, meaning that you refer to the first element as [0], the second as [1], etc. However, the .length property will return the actual number of elements in an array. So if we add 10 elements to our array, asking for the length will give us 10.
So what the person who wrote that code is doing, is using the fact that the .length property will allow you to target an element of the array that doesn't exist yet -- the element after the last element.
So for example, say we have an array with 10 elements. The length property will be 10, however the index of the last item will be nine, since the indices are zero-based. When the author of that code does:
namesArray[namesArray.length] = userInput;
They're also saying namesArray[10] = userInput;, and assigning userInput to the eleventh spot in the array (remember, zero-index).
Since this can be a little confusing to follow, most programmers will simply use the .push() method, which automatically tacks the value you pass it onto the end of the array without you having to specify an index.
Since arrays are indexed starting from zero, the last element in the array always has the index
namesArray.length - 1
Therefore, the next available unused index is always equal to
namesArray.length
You can safely set values at this index and know that they will be added to the end of the array.
So, you have this array:
var namesArray = new Array();
And you may know you can insert array values like this:
namesAray[0] = 'first value';
namesAray[1] = 'second value';
namesAray[2] = 'third value';
Now, the code is like this:
namesArray[namesArray.length] = userInput;
So, here the namesArray.length brings you the size of the array. Ok, as above you see I've added three values to the namesArray namesArray[0],namesArray[1], namesArray[2]. So the current size of the array is 3 and namesArray[namesArray.length] is equal to namesArray[3] and now here the input value is inserted.
So, like this the code inserts new array value to the end index of array which is checked by while ( (userInput = prompt("Enter name", " ")) != " ") {
Hope you understood.

How do I use #DbLookup results to populate a Readers field in xpages?

db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)

Categories