I'm trying to push to an array even numbers inside an arrow function but I don't how to push it in to that array.
My code:
var arrayEvenNumbers = [];
var evenNumbers = (arrayEvenNumbers) => {
for (i = 2; i <= 20; i++) {
if (i % 2 == 0) {
arrayEvenNumbers.push(i);
}
}
}
console.log(evenNumbers(arrayEvenNumbers));
Really I'm a beginner and I've learned a bit, but I'm trying my best
Hope someone could help me to improve
Also I don't know if I'm sending the arguments properly
And I'm not native english speaker so excuse if I can't express correctly :)
this way
var arrayEvenNumbers = [];
const evenNumbers = arr =>
{
for (let i = 2; i <= 20; i++)
if (i % 2 == 0) arr.push(i);
return arr
}
console.log( evenNumbers(arrayEvenNumbers) )
console.log( arrayEvenNumbers )
evenNumbers pushes it correctly, but returns undefined. You're probably looking to do:
evenNumbers(arrayEvenNumbers);
console.log(arrayEvenNumbers);
this is the code you've forgotten the return statement:
var freeArr = [];
var evenNumbers = (arr)=>{
for(i = 2; i <= 20; i++){
if(i % 2 == 0){
arr.push(i);
};
};
return(arr);
};
console.log(evenNumbers(freeArr));
Related
newbie JavaScript question.
This function is supposed to make a route cipher out of a given string.
Why is this resulting in an infinite loop?
function routecipher(string, rows, columns){
var mArray = string.split('')
var newArray = []
for (i = columns; i < mArray.length; i+=columns) {
for (j = 0; j < mArray.length - columns; j+columns){
newArray.push(mArray.slice(j, i))
}
}
}
Edit: There were several blunders. What was causing the infinite loop was j+columns instead of j+=columns. This is the new working code.
function encryption(string, r, c){
var mArray = string.split('')
var newArray = []
for (i = c; i <= mArray.length; i+=c) {
for (j = i - c; j < i; j+=c){
newArray.push(mArray.slice(j, i))
}
}
}
I think you really want to do like:
function routecipher(string, columns, rows = Infinity){
let s = string.split(''), a = [], r = 0;
while(s.length && r < rows){
a.push(s.splice(0, columns)); r++;
}
return a;
}
console.log(routecipher('I have no idea what this string is supposed to contain', 3));
console.log(routecipher('I have no idea what this string is supposed to contain', 4, 5));
Maybe because in the second loop there is no assignment on the 3rd parameter of the loop. Maybe you meant “j += columns” instead of just “j+columns”.
I think j+columns should be j+=columns. The equal sign is missing.
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exists in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [6,5,5]
Output: 2
My code:
let newHash = {};
let local = 0;
let global = 0;
for (let num of nums){
if (newHash[num]){
newHash[num] += 1
} else {
newHash[num] = 1
}
for (let num in newHash){
console.log(num)
local = Math.max(newHash[num], newHash[num] + local)
if (local > global){
global = local
console.log(global)
}
console.log(local)
}
return num
}
};
I pass the first example [3,2,3] but fail on [6,5,5]. I know I am super close but cannot figure out how to pass.
Since the majority element will always exist, you can just find the element that has the highest frequency.
function solve(nums){
let newHash = {};
let max = 0, res;
for (let num of nums){
if (newHash[num]){
newHash[num] += 1;
} else {
newHash[num] = 1;
}
if(newHash[num] > max){
max = newHash[num];
res = num;
}
}
return res;
}
console.log(solve([6,5,5]));
I guess you're solving LeetCode's 169, for which this'll pass through:
const majorityElement = function(nums) {
const map = {};
for (let i = 0; i < nums.length; i++) {
map[nums[i]] = map[nums[i]] + 1 || 1;
if (map[nums[i]] > nums.length >> 1) {
return nums[i];
}
}
};
Or a bit easier to understand:
const majorityElement = function(nums) {
const map = {};
for (let i = 0; i < nums.length; i++) {
map[nums[i]] = map[nums[i]] + 1 || 1;
if (map[nums[i]] > nums.length / 2) {
return nums[i];
}
}
};
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Array Length in JavaScript
I made the following code to generate an array of primes till a number 'num'.
But It is giving totally unexpected results.
I tried debugging it on chrome but the debugger does not help much as it just skips over the 4th line.
function Sieve(num) {
var arr = Array.from({length:num-1}).map((x,i)=> i+2);
var numb = Math.floor(Math.sqrt(num));
var arra = Array.from({length:numb-1}).map((x,i)=> i+2);
arra.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y=!x)));
console.log(arr);
}
Sieve(10)
Is this supposed to be Sieve of Eratosthenes algorithm? Just to mention, you know this is not the fastest way to generate primes?
Bersteins's primegen is confirmed faster, and they might be even faster solutions.
That aside, let's display simple code for what you are trying to achieve:
var eratosthenes = function(n) {
// Eratosthenes algorithm to find all primes under n
var array = [], upperLimit = Math.sqrt(n), output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if(array[i]) {
output.push(i);
}
}
return output;
};
This is far simpler to understand and split in sections.
BTW, you know Array.from(new Array(n-1), (x,i) => i+2); works? There is no need to array.from() and then .map(), you can pass map function directly into from as a parameter. Also with new Array(n) code is a bit more readable.
This is solution using your principles.
function Sieve(num) {
var arra = Array.from(new Array(num-1), (x,i) => i+2);
var comb = Array.from(new Array(Math.sqrt(num)-1), (x,i) => 2+i);
comb.forEach(x => arra=arra.filter(y => (y%x !== 0) || (y===x) ));
console.log(arra);
}
Sieve(100);
It's on CodePen since JSFiddle breaks. labda solution to Erathostene's sieve
Very new, trying to make a function that takes out and separates all negatives/positives/zeros in an array. So far Ive been able to make an acceptable for loop but only with hard coded numbers. Dont currently know how to convert it into a function. please help.
var arr=[1,3,5,-9,-3,0];
var new_arr = [];
var new_arr2 = [];
var new_arr3=[];
for(i =0; i < arr.length; i++){
if(arr[i]>0){
new_arr.push(arr[i]);
}
else if(arr[i]<0){
new_arr2.push(arr[i]);
}
else if(arr[i]===0){
new_arr3.push(arr[i]);
}
}
console.log(new_arr3.length/arr.length);
console.log(new_arr2.length/arr.length);
console.log(new_arr.length/arr.length);
How about something like this?
function division(arr) {
var new_arr = [];
var new_arr2 = [];
var new_arr3 = [];
for (i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
new_arr.push(arr[i]);
} else if (arr[i] < 0) {
new_arr2.push(arr[i]);
} else if (arr[i] === 0) {
new_arr3.push(arr[i]);
}
}
console.log(new_arr3.length / arr.length);
console.log(new_arr2.length / arr.length);
console.log(new_arr.length / arr.length);
}
division([1, 3, 5, -9, -3, 0]);
This new function takes the array as a parameter, so all you need to do is call it and pass the array.
You can try this way also, here I am considering 0 as a positive number. If you want, you can tweak the condition as per requirement.
function positive_negative(array ){
positive = array.filter(function (a) { return a >= 0; });
negative = array.filter(function (a) { return a < 0; });
return [positive,negative];
}
var array = [1,3,5,-9,-3,0];
console.log(positive_negative(array));
Have been stuck on this for a while:
I tried converting the code below to for each statements,and i ended up with errors.
ChartClass.prototype.dataTranslatorLine = function(data) {
jsonLength = Object.keys(data).length;
for (j = 0; j < jsonLength; j += 2) {
var innerObjArray = new Array();
positionNumber = Object.keys(data[j].position).length;
for (k = 0; k < positionNumber; k++) {
var obj = {};
obj.x = data[j].position[k];
obj.y = data[j + 1].position[k];
innerObjArray.push(obj);
}
dataArray.push(innerObjArray);
}
return dataArray;
};
Can anyone help me out with this?
Check out my fiddle here
I'm not entirely sure what is going on, but this should be a pretty direct translation to using forEach.
ChartClass.prototype.dataTranslatorLine = function(data) {
var dataArray = [];
Object.keys(data).forEach(function(key, idx) {
if (idx % 2 === 1) {
return;
}
var innerObjArray = [];
Object.keys(data[idx].position).forEach(function(key2, idx2) {
var obj = {
x: data[idx].position[idx2],
y: data[idx + 1].position[idx2]
};
innerObjArray.push(obj);
});
dataArray.push(innerObjArray);
});
return dataArray;
};
A couple of notes though: if data is an array, there is no need to call Object.keys on it, just go directly for the iteration; this code is rather convoluted, and I would think that with some work on the data structure being passed in could make more sense; and a for loop may be better for you situation instead of the forEach loop since you are primarily working on index instead of doing stuff just with the values.
EDIT:
After looking at your data structure this is a quick and dirty way to do it, but I still suggest you rework how you are storing your data into something that makes more sense.
ChartClass.prototype.dataTranslatorLine = function(data) {
for (var i = 0; i < data.length; i += 2) {
x = data[i].position;
y = data[i + 1].position;
var innerObj = [];
for (var j = 0; j < x.length; j++) {
innerObjArray.push({
x: x[j],
y: y[j]
});
}
dataArray.push(innerObj);
}
return dataArray;
};
The forEach doesn't buy you anything since you are working with indexes, not just the contents of the array. As for what key is in Object.keys(data).forEach(function(key, idx) { for you it will be the strings 'name' and 'position' since you are iterating over the keys of the object. Also, if (idx % 2 === 1) { return; } is how it is mimicking the j += 2 from your original for loop, basically exiting the function if it is an odd index.