Question a:
(i) Write a JavaScript code fragment that obtains four strings from text fields, stores them in an array, uses the sort function to sort it into ascending lexicographical order, and displays the sorted array in a presentation tag on the HTML page from which the script was invoked. All interactions with the document object model should be done using JQuery. You should assume that the input fields have id attributes id1, id2, id3, and id4, and the presentation tag has the id attribute sorted
Solution I found:
$(document).ready(function(){
var strings =[$("#id1").val(),$("#id2").val(),$("#id3").val(),$("#id4").val()];
strings.sort();
$("#sorted").text(strings);
alert(strings);
});
I have a question about that solution: What is the alert(strings); line for? I know what the alert function does but I don't see the question asking for it.
(ii) Describe how the code produced for part (a) would need to be modified to sort numbers into ascending numerical order
It seems to be the code above already sorts numbers into ascending numerical order, am I wrong?
What is the alert(strings); line for?
Just to show the result.
It seems to be the code above already sorts numbers into ascending numerical order, am I wrong?
That's incorrect. If you don't provide a callback, sort defaults to a lexicographic sort (loosely speaking, it sorts alphabetically), converting the elements to strings (for the sort comparison only) if necessary:
const a = [3, 10, 7, 20];
a.sort();
console.log(a);
Notice how 10 comes before 3, because the string "10" sorts before the string "3" in a lexicographic sort, because "1" is before "3".
Related
I wanted to use a set in javascript and I found in docs we have Set in js.
But when I tried to use it, it doesn't returns the elements in sorted order.
let mySet1 = new Set()
mySet1.add(1) // Set [ 1 ]
mySet1.add(5) // Set [ 1, 5 ]
mySet1.add(5) // Set [ 1, 5 ]
mySet1.add(15)
mySet1.add(150)
mySet1.add(23)
mySet1.add(45)
console.log(mySet1)
Set(6) {1, 5, 15, 150, 23, …}
[[Entries]]
0: 1
1: 5
2: 15
3: 150
4: 23
5: 45
size: (...)
Isn't the set implemented using a Binary Search Tree like structure in javascript as in other languages like C++, Java
What will be the time complexity for insertion, deletion here.
Or are they HashSet??
Isn't the set implemented using a Binary Search Tree like structure in javascript as in other languages like C++, Java
No, because that wouldn't make any sense - sets very often have non-numeric values in them, and may even have non-serializable values like functions and class instances. Binary search only works for numbers (or for values that can be serialized and converted into numeric values one-to-one, like strings)
But when I tried to use it, it doesn't returns the elements in sorted order.
The order in which values are iterated over is their insertion order, not their sorted order.
What will be the time complexity for insertion, deletion here.
See here. It's required to be at least sublinear. Past that is up to each individual implementation.
Given an array of objects, calculate the tag that produces the highest "num" most often.
I'm having an issue where the num represents level of happiness, and I'm trying to find the tag that leads to the highest level most often.
Example of array:
[{num: 5, tags:["friends", "family"]}, {num: 1, tags:["friends", "work"]}, {num: 4, tags:["school"]}]
The family tag would get a lot of points cause it appears with a 5. Friends would get points too, but then be disadvantaged because of the one.
This problem is supposed to be a little obscure. There's no one way to do it. If you have any suggestions for how, please leave a comment! If you have code, even better:).
Thank you!
This looks like homework or a job interview question, so I'm going to make suggestions rather than full solutions.
You have an input data structure; think about what your output data structure should look like. Coding then becomes a simple matter of transforming one to the other.
One possibility is a simple object, treating the tags as keys and their num as values, something like:
{friends: 5, family: 5, work: 1...}
...but this means you have to make decisions about what happens when the same tag has more than one value. Do you only care about the highest value for a given tag? Do you want the average of all values? Do you want a confidence interval? (i.e. if there are fifteen instances of tag A, and only one instances of tag B, the values for A are more likely to be "correct".) This is the part that requires some interpretation of the question.
So that implies that instead of keeping track of only a single value for each tag, maybe you need to keep track of all of them, so for every tag you'll be able to see how many scores it received, and what they were:
{friends: [1, 5], family: [5], work: [1]...}
...and then as a final pass can go through those arrays and perform whatever interpretation of the data you decided on above, resulting in a single number for each tag.
So now that you know what you're converting to, the algorithm is pretty obvious:
Initialize an output object
for each object in the source array,
for each tag in the object's "tag",
if the tag doesn't exist yet in the output object, create it as a new object key, with an empty array as its value
push the "num" value onto that array
for each key in the output object,
Do Something™ to its values array to convert it into a single value
Pretty easy with the lodash countBy function.
const theArray = [{num: 5, tags:["friends", "family"]}, {num: 1, tags:["friends", "work"]}, {num: 4, tags:["school"]}];
const allTags = [];
theArray.map((item) =>{
allTags.push(...item.tags);
} );
const count = _.countBy(allTags);
console.log(count);
https://jsfiddle.net/m7L1prau/
I would like a function in JavaScript, where I can obtain an array with the corresponding positions of an Array of numbers, where adding their values results in the number that I want to obtain.
New.
I need return only one response, although there are other possible ones.
Although the ideal answer is the longest array.
Example 1:
I have the Array with the following numbers:
[9,4,11,6,3,5,7]
I want to obtain an array where the sum of its values gives me the value 7
Desired response: [1,4]
Example 2:
With the same starting array as Example 1, I want to obtain the value 14
Desired response: [1,4,6]
From already thank you very much.
I've read this [SO post][1], it has helped, but it looks like it has played around with the data...
I have read in two CSV files that look like this:
word, frequency
random, 462546
stupid, 34652
dumb, 4346
I've merged them, which works. I've sorted them, however, it half works. The sorting function sorts the two array of objects as if they were separate. What I mean by this, is that my two arrays of objects merge together, but it has merged them one after another. Then sorted one array of objects, then sorted the other, without sorting them as one whole array, it's sorting them as two arrays.
A link to my CSV files is here enter link description here
d3.csv("data/ArsenalDictionary.csv", function(error1, Arsenal) {
d3.csv("data/ChelseaDictionary.csv", function(error2, Chelsea) {
var selected = d3.merge([Arsenal, Chelsea]);
selected.sort(function(a, b){ return d3.descending(a[2], b[2]); })
console.log(selected);
});
});
Your array selected isn't getting sorted because you are attempting to sort the objects by a non-existent property.
The elements of your array are objects with two properties, "words" and " frequency" (note the leading space in the latter). You are attempting to sort them by a property named 2, which they don't have.
You would have better luck sorting them by the frequency property:
selected.sort(function(a, b){ return d3.descending(a[" frequency"], b[" frequency"]); });
Note however that this doesn't entirely do what you expect: the frequencies end up in the order 94, 9, 9, 9, ..., 8, 8, 8, ..., etc. This is because they have been sorted as strings, not as numbers.
To deal with this either convert the values to numbers while sorting (note the extra + signs):
selected.sort(function(a, b){ return d3.descending(+a[" frequency"], +b[" frequency"]); });
Alternatively, you can convert the frequencies to numbers as part of reading in the files:
function mapRow(row) {
return { "words": row["words"], " frequency": +row[" frequency"] };
}
d3.csv("ArsenalDictionary.csv", mapRow, function(error1, Arsenal) {
d3.csv("ChelseaDictionary.csv", mapRow, function(error2, Chelsea) {
// ...
The former is more convenient but the latter may come in more useful if you want to do other things with the numbers, such as add up two counts if both files use the same word. (world appears in both files).
I need help with a loop... it's probably simple but I'm having difficulty coding it up.
Basically, I need to check existing Ids for their number so I can create a unique id with a different number. They're named like this: id="poly'+i'" in sequence with my function where i is equal to the number of existing elements. Example: Array 1, Array 2, Array 3 corresponding with i=1 for the creation of Array 1, i=2 for Array 2, etc.
Right now i is based on the total number of existing elements, and my "CreateNew" function is driven off x=i+1 (so the example above, the new element will be named Array 4). The problem is that if you delete one of the middle numbers, the "Create" function will duplicate the high number. i.e. Array 1, 2, 3 delete 2, create new-> Array 1, 3, 3.
I need an if() statement to check if the array already exists then a for() loop to cycle through all i's until it validates. Not sure how to code this up.
The code I'm trying to correct is below (note I did not write this originally, I'm simply trying to correct it with my minimal JS skills):
function NewPanel() {
var i = numberOfPanels.toString();
var x = (parseInt(i)+1).toString();
$('#items').append('<div onclick="polygonNameSelected(event)" class="polygonName" id="poly'+i+'"> Array '+ x +' </div>');
$('div[id*=poly]').removeClass('selected');
$('#poly'+i).addClass('selected');
$('#poly'+i).click(function() {
selectedPolygon = i;
$('div[id*=poly]').removeClass('selected');
$(this).addClass('selected');
});
}
THANK YOU! :)
Please clarify "The problem is that if you delete one of the middle numbers, ". What do you mean by delete? Anyway, the simplest solution is to create two arrays. Both arrays will have the same created id's. Whenever an id is created in the first array, an id will be added to the second array. So when it is deleted from first array, check your second array's highest value and then create this id in first array. I hope this did not confuse you.
Well it is hard to tell why you cannot just splice the array down. It seems to me there is a lot of extra logic involved in the tracking of element numbers. In other words, aside from the index being the same, the ids become the same as well as other attributes due to the overlapping 1, 3, 3 (from the example). If this is not the case then my assumption is incorrect.
Based on that assumption, when I encounter a situation where I want to ensure that the index created will always be an appending one, I usually take the same approach as I would with a database primary key. I set up a field:
var primaryKeyAutoInc = 0;
And every time I "create" or add an element to the data store (in this case an array) I copy the current value of the key as it's index and then increment the primaryKeyAutoInc value. This allows for the guaranteed unique indexing which I am assuming you are going for. Moreover, not only will deletes not affect future data creation, the saved key index can be used as an accessor.