How to print only evens from an array? [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 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

Related

Returning the full contents of an array [duplicate]

This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
function monkeyCount(n) {
for (i=1; i<=n; ++i){
let monkeyArray=[i];
return monkeyArray[i];
}
}
Another rookie question lol. I need to return the values of an entire array using the return statement and not the console.log. If I pass a number such as 5 to the function I need to return 1,2,3,4,5 your help much appreciated:0)
It looks like you want to append values to the array not reassign the array at every iteration of the loop. Try this:
const monkeyArray = [];
for(let i = 1; i<= n; i++){
monkeyArray.push(i);
}
return monkeyArray;
There are also many ways to do this such as with the lodash library where you can just call _.range(1, 6) to get an array from [1,6)
This is pretty simple, you just have try this on browser console.
function monkeyCount(n) {
let monkeyArray = [];
for (i=1; i<=n; ++i) {
monkeyArray[i-1] = i;
}
return monkeyArray.join(',');
}

JavaScript fundamentals confusion / convert Python [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 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?

How to get sum of array with "for" loop [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 6 years ago.
I'm a total newbie in JavaScript. I'm trying to learn it using programming experience in Python...
Let's say there is an array of integers [2,3,4,5]. I want to get sum of all items in it with for loop. In Python this gonna looks like
list_sum = 0
for i in [2,3,4,5]:
list_sum += i
Result is 14
But if I try same in JavaScript:
var listSum = 0;
for (i in [2,3,4,5])
{
listSum += i;
}
This will return 00123. Seems that item indexes concatenated in a string with initial listSum value. How to make code works as intended and to get sum of all array items as integer?
You are doing wrong for loop syntax. check this : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for
var listSum = 0;
var arr = [2,3,4,5];
for (i=0;i<arr.length ; i++)
{
listSum += arr[i];
}
document.write(listSum);

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