How to store divisible number in a new array with javascript - javascript

I am trying to store the numbers that are divisible by three in the threes array. How is this done?
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push([i]);
console.log(threes);
}
} return threes
};
iLoveThree();

There were a few problems.
You needed to access the number in the array using the index numbers[i] rather than just checking the index.
You also needed to pass the two parameters to the iLoveThree function.
Here is the working code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
var iLoveThree = function (numbers, threes) {
for (i in numbers) {
if (numbers[i] % 3 === 0) {
threes.push(numbers[i]);
}
}
return threes;
};
console.log(iLoveThree(numbers, threes));
// [3, 6, 9]
As a side note, you could simplify your code by using the .filter() method.
If the boolean num % 3 === 0 is true, then the number isn't removed from the array.
var numbers = [1,2,3,4,5,6,7,8,9].filter(function (num) {
return num % 3 === 0;
});
console.log(numbers);
// [3, 6, 9]

you put brackets around i when you did the push. You do not need the brackets.
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push(i); //don't put brackets here
console.log(threes);
}
} return threes
};

Here you go:
var numbers = [1,2,3,4,5,6,7,8,9];
function iLoveThree(numbers) {
return numbers.filter(function(n) {
return n % 3 === 0;
});
}
var threes = iLoveThree(numbers);

Try substituting for loop for..in loop ; using numbers[i] number in array instead of [i] index of item within array in current iteration
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
for(var i = 0; i < numbers.length; i++)
!(numbers[i] % 3) && threes.push(numbers[i]);
console.log(threes)

Related

How do I write a function that returns the first 5 positive even numbers?

var myArr = [1,2,3,4,5,6,7,8,9,10];
function even(num) {
var newArr = [];
for (var i=1; i<num.length; i++) {
if (num[i] % 2 === 0) {
newArr.push(num[i]);
}
}
return newArr;
}
console.log(even(myArr));
My function throws an exception when called. How can I rewrite or refactor the above code to return the first 5 positive numbers?
You can create it this way.
var myArr = [1,2,0,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
let evens = myArr.filter(x => x > 0 && x % 2 == 0).slice(0, 5);
console.log(evens)
First off, your code appears to work. Can you give an example of the error that is occurring? Second off, if you want a function that returns an array of the first n positive, even integers, you can write something like this.
function firstEven(count) {
var response = []; // Create the response list
for(var i=0;i<count;i++) { // Loop for number of even numbers you want
response.push((i + 1) * 2); // *2 skips every two numbers, and +1 shifts the number to even
}
return response
}
However, if you want to just filter out all odd numbers from an array, you can do the following.
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myEvens = myArr.filter(function(myNum) { // Filter runs the function for every value in the array, and (if the function returns false) it removed that value
return (myNum % 2) == 0;
});
Feel free to ask if you have any questions!
2 others differnts ways
const myArr = [1,2,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
const even_1 = arr => arr.filter(x=>(x>=0 && !(x&1))).slice(0,5)
const even_2 = arr =>
{
let r = []
for(x of arr)
if (x>=0 && !(x&1)) // test2 = boolean AND on bit zero
{
r.push(x);
if (r.length >= 5) break;
}
return r
}
console.log('even 1:', even_1(myArr).join(','))
console.log('even 2:', even_2(myArr).join(','))
One suggestion:
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function even(numbersArray) {
var first5EvenNums = [];
for (const num of numbersArray) {
if (first5EvenNums.length >= 5) break;
if (num % 2 === 0) {
first5EvenNums.push(num);
}
}
return first5EvenNums;
}
console.log(even(myArr));
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="test"></div>
<script>
var myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
function even(num){
var newArr = [];
for (var i=1; i<num.length; i++){
if (num[i] % 2 === 0)
{
newArr.push(num[i]);
if(newArr.length == 5){
return newArr;
}
}
}
return newArr;
};
$("#test").text(even(myArr));
</script>
This return first 5 positive number in array.

How to find the largest group of numbers in an array and return them separately in javascript?

How can I make a function that returns only the numbers greater than the number that I entered?
My code here isn't working, and I don't know why.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function findBiggestNumbers(num) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
num = arr[i];
}
}
return num;
// }
console.log(findBiggestNumbers(num));
To work with arrays you could use the filter function, it returns a subset of the array with some condition. So, you can simpley do:
var num = 5; //using 5 as an example
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = a.filter(number => number > num);
You can put this into an function.
You need to create a new empty array and fill it with numbers that are bigger than input value.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function FindBiggestNumbers(num) {
let biggerThanArray = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
biggerThanArray.push(arr[i]);
}
}
return biggerThanArray;
}
console.log(FindBiggestNumbers(num));
You can start to understand and do some fun things with functional JS.
Similar to the answer from Daladier Sampaio I've used filter to return an array where each element passes a condition (el > num) in the callback function. (filter, reduce, and map were introduced in ES5 and are very useful array methods and well worth learning how to use.)
In this example, I've passed in - and called - a whole function named greaterThan instead.
greaterThan
1) Accepts an argument - n, the number from the prompt in this case
2) Returns an array - the callback function that will operate on each array element. What's interesting about this function is that it carries a copy of num with it when it returns. A function like this that retains a copy of its outer lexical environment like that is called a closure. Understanding what they are and how they work is a useful JS skill, and one that is often picked up on in JS interviews.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const num = Number(prompt('number'));
// accepts a number and returns a callback function
// that accepts an array element and
// tests it against the value of `n`
function greaterThan(n) {
return function (el) {
return el > n;
};
}
// calling greater than with our prompted number
// returns that new callback function that checks each
// array element
const out = arr.filter(greaterThan(num));
console.log(out);
Modern JS >= ES6 will allow you to condense the amount of code you have to write using arrow functions. The following one-line code will work in place of the function in the example:
const greaterThan = n => el => el > n;
You could use Array.prototype.filter():
function FindBiggestNumbers(num) {
return arr.filter(n => n > num);
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));
The alternative is using a nested if statement inside a for loop like so:
First make a new array:
function FindBiggestNumbers(num) {
var newArr = [];
}
Then loop through the original array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
}
}
And if you find an element of the array greater than the number, add it to the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
}
Finally, return the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
Demonstration:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.
I'm not sure if there's a better way to do this, and I'm stuck. Is there a way to return both statements?
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
console.log(evens);
console.log(odds);
//I need it to "return" the array,
//not console log
}
console.log(oddsAndEvens(myNums));
A clean function to separate the evens from the odds.
function arrangeNums(array) {
let odd = array.filter(i=>i%2!==0);
let even = array.filter(i=>i%2===0);
return {even:even,odd:odd};
}
console.log(arrangeNums([...Array(100).keys()]));
return arrays instead of console.log should work
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
// return array of values you want
return [evens, odds]
}
console.log(oddsAndEvens(myNums));
You could use an object for the result and taken an array for the keys of the object to push the value.
function getGrouped(array) {
return array.reduce(function (r, a) {
r[['even', 'odd'][a % 2]].push(a);
return r;
}, { odd: [], even: [] });
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
console.log(getGrouped(myNums));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Off course you can, just return an object containing both evens and odds,
function oddsAndEvens(nums)
{
var evens = [];
var odds = [];
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
return {"evens":evens,"odds":odds};
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
result = oddsAndEvens(myNums);
console.log(result.evens);
console.log(result.odds);

Count number of values in array between two input values

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the array was [1, 4, 6, 7, 8, 6] and the user entered 5 as their first value and 7 as their second value, they would be greeted with an alert that said
"total number of values = 3".
You can create an extremely clean solution to this problem by utilizing the second property of Array#filter (which sets the this binding given to your callback of choice):
var array = [1, 4, 6, 7, 8, 6]
function inRange (x) {
return this[0] <= x && x <= this[1]
}
var result = array.filter(inRange, [5, 7]).length
console.log('Total number of values:', result)
All you need is a simple for loop.
var total = 0;
var num1 = 5;
var num2 = 7;
var array = [1,4,6,7,8,6];
for(var a = 0; a < array.length; a++) {
if(array[a] >= num1 && array[a] <= num2) {
total++;
}
}
alert("Total numbers of values = " + total);
This will loop through the array, detect nums within the range, tally up a value, and output it in a alert.
You can use Array.prototype.filter(), RegExp.prototype.test() with RegExp constructor with class from-to, where from is 5, to is 7, get .length of resulting array
var from = 5;
var to = 7;
var len = arr.filter(RegExp.prototype.test.bind(new RegExp(`[${from}-${to}]`))).length;
You can alternatively use .toString(), .match()
var arr = [1,4,6,7,8,6];
var from = 5;
var to = 7;
var res = arr.toString().match(new RegExp(`[${from}-${to}]`, "g"));
var len = res.length;
console.log(res.length);
You may do as follows;
var arr = [1,4,6,7,8,6],
input = [5,7],
result = arr.reduce((r,n) => n >= input[0] && n <= input[1] ? ++r : r, 0);
console.log(result);
var array = [1, 4, 6, 7, 8, 6];
function countNumber(arr,a,b){
let count = 0;
for (const number of arr){
if (number >= a && number <= b){
count ++;
}
}
return count;
}
console.log(countNumber(array, 5, 7));

Check if random numbers in array contains 5 of them in ascending order

Hello I want to check if 5 random numbers in array are ascending.
Example from this:
var array = [2, 5, 5, 4, 7, 3, 6];
to this:
array = [2,3,4,5,6];
and of course if higher sequence is possible:
array = [3,4,5,6,7];
Is there any shortcut for this kind of sorting in jQuery?
Thanks in advance.
var array = [2, 5, 5, 4, 7, 3, 6];
//first convert into an object literal for fast lookups.
var ao = {};
array.forEach(function (e) { ao[e] = true; });
//now loop all in array, and then loop again for 5
array.forEach(function (num) {
var count = 0, l;
for (l = 0; l < 5; l ++) {
if (ao[num + l]) count ++;
}
if (count === 5) {
//found, push into array just to show nice in console
var nums = [];
for (l = 0; l < 5; l ++) {
nums.push(num + l);
}
console.log(nums.join(','));
}
});
I think, this will do the trick:
get unique members
sort them
slice last 5
(or reverse, slice first 5, reverse) like I did, since your array could be less then 5.
If resulting array has length of 5 then you have a positive answer.
console.log($.unique([2,5,5,4,7,3,6]).sort().reverse().slice(0,5).reverse())
You might do as follows;
function checkStraight(a){
var s = [...new Set(a)].sort((a,b) => a-b);
return s.length >= 5 && s.reduce((p,c,i,a) => c - a[i-1] === 1 ? ++p
: p < 5 ? 1
: p , 1) > 4;
}
var array = [2, 5, 5, 4, 7, 3, 6, 9],
result = checkStraight(array);
console.log(result);

Categories

Resources