i'm spending way too much time on trying to figure these 2 codes out.
i'm too burn out. i spent the last 2 hrs and lots of hours trying to figure out why Code 1 doesn't accept. And for Code 2, it accepted, but i'm not too sure.
Code 1.
Given an input Object, how might we loop over the Object IN REVERSE and
print its values using console.log()?
function printObjectValuesInReverse(object) {
var myArray = [];
for(var keys in object) {
myArray.push(object[keys]);
}
for(var i = keys.length-1; i >= 0; i--) {
console.log(keys[i]);
}
Code 2
Given an Array of Strings and a Function designed to test the String in some way and return a Boolean on whether it passed, return true if ALL Strings pass the test.
function allStringsPass(strings, test) {
for (var i =0; i < strings.length; i++) {
if(test(strings[i]) === false) {
return false;
}
}
return true;
You can simply use reverse function. so your console.log will be console.log(myArray.reverse())
Update if you dont want to use a reverse function, your code should be like this
function printObjectValuesInReverse(object) {
var myArray = [];
for(var keys in object) {
myArray.push(object[keys]);
}
for(var i = myArray.length-1; i >= 0; i--) {
console.log(myArray[i]); // I changed this from keys[i]
}
}
printObjectValuesInReverse({a: 1, b: 2, c: 3})
Code 1
keys isn't an array. I think you might wanna iterate over myArray.
function printObjectValuesInReverse(object) {
var myArray = [];
for(var keys in object) {
myArray.push(object[keys]);
}
for(var i = myArray.length-1; i >= 0; i--) {
console.log(myArray[i]);
}
}
Code 2
Just but the closing brace and it should work fine:
function allStringsPass(strings, test) {
for (var i =0; i < strings.length; i++) {
if(test(strings[i]) === false) {
return false;
}
}
return true;
}
Related
I am trying to accomplish the following:
consider an array of integers of size N. You should find and print the position of all the elements with value X. You can choose the variables and values.
Here are my variables:
var numLocation = [];
var givenNum = 8;
var arr = [0,8,1,2,4,5,7,8,9,0,8]
This is my function
function indexPosition(arr) {
for(var i = 0; i <= arr.length; i++) {
if (arr[i] === givenNum) {
numLocation.push(i)
} else {
console.log (numLocation)
}
}
}
This is my result after calling the function:
[]
[1]
[1]
[1]
[1]
[1]
[1,7]
[1,7]
[1,7,10]
How do I only show the last iteration where it shows the three positions where the number 8 is located at? Meaning, How can I console.log only the final result?
Call the log statement outside of your for loop. Like so:
function indexPosition(arr, givenNum) {
var numLocation = []
for (var i = 0; i <= arr.length; i++) {
if (arr[i] === givenNum) {
numLocation.push(i)
}
}
console.log(numLocation)
}
I am trying to practice my algorithm skills. I know there is already an algorithm written out there, I just want to try it on my own and see how close i could get.
INPUT:
arr1 = ['asd','ew','lol','asd']
EXPECTED OUTPUT:
{ asd: 2, ew: 1, lol: 1 }
This is my code:
arr1 = ['asd', 'ew', 'lol', 'asd']
arr2 = []
results = {}
function checkIfExists(word) {
if (arr2.length != 0) {
for (i = 0; i < arr2.length; i++) {
if (arr2[i] == word) {
results[word] += 1
} else {
arr2.push(word)
results[word] = 1
}
}
} else {
arr2.push(word)
results[word] = 1
}
}
for (i = 0; i < arr1.length; i++) {
checkIfExists(arr1[i])
}
console.log(results)
ACTUAL OUTPUT:
{ asd: 2, ew: 2 }
You used i as a global variable, so don't use for two loop. Other mistake is in your increment algorithm that add more than needed count to results array. So try it:
arr1 = ['asd','ew','lol','asd']
arr2 = []
results = {}
function checkIfExists(word){
if (arr2.length != 0){
var exists = false;
for (var j = 0; j < arr2.length; j++){
if(arr2[j] == word){
results[word] += 1
exists = true;
break;
}
}
if(!exists) {
arr2.push(word)
results[word] = 1
}
}else{
arr2.push(word)
results[word] = 1
}
}
for (var i = 0; i < arr1.length; i++) {
checkIfExists(arr1[i])
}
console.log(results)
There are three questions I identified immediately which you might have intended to ask.
What's wrong with my code?
I couldn't phrase this better than Felix Klings comment:
The first problem is that you are not using var to declare i.
The loop presumably intended to locate an item within arr2 also modifies arr2... a lot!
Why is my code producing incorrect output? Your code is actually producing correct output for the logic it expresses. I suspect the issue is that the logic it expresses doesn't match the logic you intended to express. This isn't uncommon
How do I fix my code?
Start by changing your loop idioms from for (i = ...) to for (var i = ...).
Think about the purpose of that loop. If it's intended to locate an item within arr2, then it shouldn't need to modify arr2 to do so. Perhaps you don't need the loop;
You could probably use Array.prototype.indexOf or Array.prototype.includes in place of that entire loop!
You could probably use function checkIfExists(word) { results[word] = arr1.filter(function(w) { return w === word; }).length; } in place of that entire function!
It seems like you could use some higher-level awareness when designing functions, so perhaps it might be a good idea to try to wrap your head around some of the elements in this code:
var arr1 = ['asd','ew','lol','asd'];
var result = arr1.reduce(function(result, w) { result[w] = result[w] || 0;
result[w]++;
return result; }, {}));
console.log(result);
In the following code there is a console log of obj['mn'] which returns the length of that specific object which is 2. The problem with the code is that it doesn't count the multidimentional array, and only it counts the first array. The result should be 4 because there are 4 'mn' in total. What am I doing wrong?
var arr = [['ab','pq','mn','ab','mn','ab'],'mn','mn'];
var obj = { };
for (var i = 0, j = arr.length; i < j; i++) {
if (obj[arr[i]]) {
obj[arr[i]]++;
}
}
console.log(obj['mn']);
This is what you're looking for:
var arr = [['ab','pq','mn','ab','mn','ab'],'mn','mn'];
var obj = { };
function count(arr, obj) {
for (var i = 0, j = arr.length; i < j; i++) {
if (Array.isArray(arr[i])) {
count(arr[i], obj);
}
else if (typeof obj[arr[i]] !== 'undefined') {
obj[arr[i]]++;
}
else {
obj[arr[i]] = 1;
}
}
return obj;
}
console.log(count(arr, obj));
This is a recursive implementation. When it gets to an array, the recursion get one level deeper.
You are calling obj[['ab','pq','mn','ab','mn','ab']], which is obviously not what you wanted.
You need a depth first search.
If arr[i] is an array, then you need to loop through that array.
charFreq function that's not quite working out. Hit a wall. I know I may need to
do a conditional. Calling the function returns an Object error. I'm attempting
to get string into an empty object displaying the characters like this - Object
{o: 4, p: 5, z: 2, w: 4, y: 1…}. New to Javascript by the way.
Just realized I shouldn't be appending anything. Do I need to do a .push() to
push the array into the object?
function charFreq (string){
var emptyObj = {};
for(var i = 0; i < string.length; i++) {
// console.log(string.charAt(i));
var args = [string.charAt(i)];
var emptyArr = [''].concat(args);
emptyObj += emptyArr
}
return emptyObj
}
undefined
charFreq('alkdjflkajdsf')
"[object Object],a,l,k,d,j,f,l,k,a,j,d,s,f"
You just need to set emptyObj's key of that specific letter to either 1 if it doesn't exist or increment the count if it already does.
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
if (!obj.hasOwnProperty(string[i])) {
obj[string[i]] = 1;
} else {
obj[string[i]]++;
}
}
return obj;
}
console.log(charFreq('alkdjflkajdsf'));
Try this instead: you need to create an object property first, then increment it. What you do, is implicitly convert the object to a string and concatenate more string data to it (using += and concat).
This is a simple approach:
function charFreq(string){
var emptyObj={};
for(var i=0; i<string.length; i++) {
if(!emptyObj.hasOwnProperty(string[i])){ // if property doesn’t exist
emptyObj[string[i]]=0; // create it and set to 0
}
emptyObj[string[i]]++; // increment it
}
return emptyObj;
}
A modified version of Richard Kho's code:
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
var c=string[i];
if (c=='') continue;
if (obj[c]==null) obj[c]=0;
obj[c]++;
}
return obj;
}
At the moment I'm trying to compare the contents of 2 arrays using the for..in loop but with no success. I'm familiar with how to get the contents of each array separately but not sure how to then match each of these contents up. Basically if 2 values in the same index values of the array don't match I want to return false else carry on. My latest attempt I've tried placing both arrays in the same for..in using different variables then comparing these. If anyone could advise on this that would be great.
JS
var list1 = [1, 2, 3, 4, 5, 6];
var list2 = [1, 2, 3, 4, 5, 'e'];
var i, j;
for (i in list1 && j in list2) {
if (list1[i] !== list2[j]) {
return false
} else {
return true
}
}
/*for ( j in list2 ) {
console.log( list2[j] )
}*/
Iteration over the elements of an array is done using the normal for loop:
if (list1.length != list2.length) {
// Different length, cannot be equal
return false;
}
// Check if there is a mismatch
for (var i = 0; i < list1.length; i++) {
if (list1[i] !== list2[i]) {
return false; // Return here, because we don't need to compare the rest
}
}
return true;
var i, l = list1.length;
for( i = 0; i < l; ++i ) {
if( list1[i] !== list2[i] ) {
return false; //Compare one by one
}
}
if( i !== list2.length ) {
return false; // In case list2 was longer than list1
}
return true;
Use a regular loop for that, and don't return true inside the loop, then you will only compare the first elements:
for (var i = 0; i < list1.length; i++) {
if (list1[i] !== list2[i]) {
return false
}
}
return true;
That only the simplest way to solve problem on sample data which were in question, rather as curiosity.
return list1.toString() == list2.toString();
It will works with the most of data exluding: strings with commas and checking for types equality.
btw.
I found other way, i think - to discuss:
return !(list1<list2 || list1>list2);
anyone?