JavaScript fundamentals confusion / convert Python [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
What I'm trying to do is take my Python code and turn it into JavaScript, yet I cannot figure out why it runs differently in JavaScript. What am I missing?
The code is intended to take an array of values with 1's and 0's and return an array summing the 1 values as such.
[1,1,0,1] => [2,1]
[0,0,1,1,1] => [3]
[0,0,0] => []
[1,1,0,0] => [2]
Python code that works (unless I'm horribly mistaken)
def encode(arr):
arr2=[]
num = 0
for i in arr:
if i==1:
num=num+1
elif i==0 and num ==0:
pass
else:
arr2.append(num)
num=0
if num>0:
arr2.append(num)
return arr2
JavaScript that doesn't work
function encode(arr) {
var arr2=[];
var num = 0;
for (i in arr){
if (i==1) {
num++;
} else if (i == 0 && num == 0) {
// pass
} else {
arr2.push(num);
num=0;
}
}
if (num>0) {
arr2.push(num)
}
return arr2;
}

Instead of
for (i in arr) { ... }
you need to write
for (let i of arr) { ... }
This is because for ... in iterates the enumerable properties, i.e. the array indices. But you want to iterate the array values.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in and also Why is using "for...in" with array iteration a bad idea?

Related

a split-function that accept a string and splits it into value , then sum them up [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
//Write a function ‘SplitFunction’ that accepts the string ‘7+12+100’ and splits it into individual values, then summing these values. (Make use of the split() and parseInt() functions). Return the summed result.
you can see the question above, and my code for this question is:
function SplitFunction(str){
let y=str.split('+')
let sum=0
for(i=0;i<y.length;i++){
sum+=parseInt(y[i])
return sum
}
}
console.log(SplitFunction('7+12+100'))
But I keep getting results as 7??? and cant find out why
Just move return sum beyond for loop
function SplitFunction(str) {
let y = str.split('+')
let sum = 0
for (i = 0; i < y.length; i++) {
sum += parseInt(y[i])
}
return sum
}
console.log(SplitFunction('7+12+100'))
Edit: or you can use this clear code below:
var SplitFunction = str => { // taking function called SplitFunction which takes an argument str
let sum = 0 // set a variable to sum up
str.split(+).forEach(number => { // split taken problem and for each of them:
sum += parseInt(number) // cast to Number and add to sum
})
return sum // finally return result
}

How to filter arrays with a for loop without the filter function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Our task is to write a function which filters a list of human names. The result should be only names without a hyphen ("-").
The only ideas I have till now:
let names = ['Marc', 'Stephen-Peter', 'Lisa', 'Marie-Tina', 'Philip'];
function filter (arr) {
for (let i = 0; i < arr.length; i++) {
??????;
}
return ???;
}
console.log(???);
//The result should be only Marc, Lisa, Philip
My ideas were to use charAt and check every word for a "-" but then I don't know how to prevent that the whole name with the hyphen is not inside the new filtered array. I thought about two for loops I don't know how to do that.
first the array items need to be inside single or double quotes
let names = ['Marc', 'Stephen-Peter', 'Lisa', 'Marie-Tina', 'Philip'];
function filter (arr) {
let result = []
for (let i = 0; i < arr.length; i++) {
if(!arr[i].includes('-')) {
result.push(arr[i])
}
}
return result
}
console.log(filter(names))
Building up on your idea, i think you just need to use an if condition and a new array to which you pass the filtered values.
let names = ['Marc', 'Stephen-Peter', 'Lisa', 'Marie-Tina', 'Philip'];
function filter (arr) {
let ans =[];
for (let i = 0; i < arr.length; i++) {
if(arr[i].indexOf('-') === -1)
ans.push(arr[i]);
}
return ans;
}
console.log(filter(names));
PS: Your list of names were not string enclosed. Please ensure you do that whenever posting a ques/ans. Also try to use code snippets.

How to print only evens from an array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently learning to code. I have to create an array and then create a function that prints only the even numbers from the array. Here is what I currently have. I am at a loss on what to do. I am learning from Code Highschool. It is what my class is making us use.
Instructions from codehs:
Write a function called
function onlyEvens(arr)
That takes an array and returns an array with only the even numbers in the original array.
Then, you should print out the new list.
How do I get the code to only print the even numbers that are in the array?
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
println(evens);
}
function onlyEvens(arr){
}
Simply you can use like this
start();
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
console.log(evens);
}
function onlyEvens(arr){
evenArr={};
for (var i = 0,j=0 ;i < arr.length; i++) {
if(arr[i] % 2 === 0) { //
evenArr[j] = arr[i];
j++;
}
}
return evenArr;
}
https://jsfiddle.net/n3jke25n/
The operator you're looking for is the modulus operator.
For any integer variable x, if x % 2 == 1, x is odd. On the other hand, if x % 2 == 0, x is even.
Thus, write an if statement that determines, using the modulus operator, whether the number in question is even; then, if it is, add it to the destination array.
Try using a modulo in onlyEvens whilst cycling the array
for (var i=0;i<arr.length;i++) {
if i%2==0 {
console.log("is even:"+arr[i])
}
}
Something like that, more here: https://en.wikipedia.org/wiki/Modulo_operation

Compare two arrays of "strings" to check if they are equal [duplicate]

This question already has answers here:
Remove items from one array if not in the second array
(5 answers)
Closed 7 years ago.
Good day,
I have two arrays of strings. Strings are just numeric dates (eg: "01/01/2016"...).
I would like to know if there is a good/fast way to compare the two arrays and remove the strings from one array, which are not present in second one.
Example:
First array: ["01/01/2016","02/02/2015", "03/03/2014"]
Second array: ["01/01/2016", "02/02/2015"]
The string "03/03/2014" should be removed from the first array.
I have tried doing it though for() loops of both array lengths, but it seems to be very slow, because the arrays are big (abt. 1000+) indexes in each, like this:
for (var a = 0; a < oilDateArray.length; a++) {
for (var b = 0; b < fuelDateArray.length; b++) {
if (fuelDateArray[b] !== oilDateArray[a]) {
console.log("fuelDateArray not present: " + fuelDateArray[b]);
}
}
}
Is there a specific function/method, which I could use in order to perform the above operation faster?
Thanks in advance and have a nice day!
Try this :
for (var i = 0; i < firstArray.length; i++){
if (secondArray.indexOf(firstArray[i]) == -1){ // indexOf is -1 if not found
firstArray.splice(i, 1); // Remove 1 value at index i
i--; // To re-adjust the index value which is 1 less because of the splice
}
}
It may also be a bit slow, you can try with your array : https://jsfiddle.net/tyrsszaw/4
with jquery
$(array1).filter(array2);
If you have access to Set:
function intersect(arr1, arr2){
var s = new Set(arr1);
return arr2.filter(function(el){
return s.has(el);
});
}
i use jquery for array operations and i'll edit one for your need and paste here, i hope this can help you:
var arr1 = ["01/01/2016","02/02/2015", "03/03/2014"];
var arr2 = ["01/01/2016", "02/02/2015"];
var diff = [];
jQuery.grep(arr2, function(t) {
if (jQuery.inArray(t, arr1) == -1) diff.push(t);
});
alert(diff);​ // what was different will be alerted
i also found this code on stackoverflow sometime ago.
Update: Here is performance related topic you might be interested
Performance of jQuery.grep vs. Array.filter
tldr;
it says grep is about 3 times faster. So stick with my solution. :)

IndexOf array with strings as index [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Probably ill advised, but I have an array with strings for indexes. Now I need to use indexOf and it doesn't work. The code below returns -1. Any way to get b out of this without rewriting everything?
x = [];
x['a'] = 0;
x['b'] = 1;
print(x.indexOf(1));
The fundamental issue you are not understanding is that an Array cannot have strings as indexes. The syntax you are using is an alternate way of defining properties on to an object. All the previous suggestions people are giving you is probably confusing you more. Keep it simple. Arrays have number indexes.
// this is adding values to an array
var x = [];
x[0] = 'one';
x[1] = 'two';
console.log(x[0]); // outputs 'one'
// this is adding a property to an object
var y = {};
y['width'] = 20;
y['height'] = 40;
console.log(y['width']); // outputs 20
console.log(y.height); // outputs 40
// this is adding a property to our previous array
// (because Arrays are objects too in JavaScript)
x['name'] = 'My Array';
console.log(x.name); // outputs 'My Array'
x.indexOf('My Array'); // returns -1 because 'My Array' is not stored in the array
x.indexOf('two'); // returns 1 because that's the index of 'two' in the array
x = [];
x['a'] = 0;
x['b'] = 1;
var valueIndex = Object.keys(x).map(function(prop){
return x[prop]
}).indexOf(1);
Object.keys(x)[valueIndex] //b
Unless it's really going to be in that order just do
Object.keys(x)[1]; //b
Concrete code for the suggestion I made in comments, depending on the scenario this is easier or harder to implement in existing code than for (prop in x):
function put(arr, letter, value) {
arr[letter.toLowerCase().charCodeAt(0)-96] = value;
}
function find(arr, value) {
return String.fromCharCode(x.indexOf(value)+96);
}
x = [];
put(x, 'a', 0);
put(x, 'b', 1);
print(find(x, 1)); // gives b

Categories

Resources