I wrote this function:
function randomProduct(num) {
var iter = num;
for (var i = 0; i < iter; i++) {
var rand = recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
return rand
}
}
Which is supposed to pull from the recommendedProducts array however many are needed when the function is called. So basically randomProduct(1) would pull 1 and randomProduct(4) would pull 4, etc.
However no matter what number I enter in there when I test is through the console, I always only get 1 array item returned.
console.log(randomProduct(1));
console.log(randomProduct(2));
console.log(randomProduct(3));
console.log(randomProduct(4));
What am I doing wrong?
try this:
function randomProduct(num) {
var iter = num;
var rand ="";
for (var i = 0; i < iter; i++) {
rand += recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
}
return rand
}
as #Steve Medley said the result expected to be string. so if recommendedProducts contains some string you should add this string in each iteration of loop to your result and return it after your loop has finished( also this is what i have understood from question)
Try this:
function randomProduct(num) {
var iter = num;
var randomArray = [];
for (var i = 0; i < iter; i++) {
randomArray.push(recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)]);
}
return randomArray.join(); // returns it as a string
}
First you need to append the items to an array using push
Second you need to return outside of the loop, if you retrun from the inside of the loop you break the function after the first iteration.
The return rand take you off the function at the first result.
You can remove the loop, just return the rand, and call the function 4 times.
If you want the function to return array of random numbers, instead of return rand, push the results to new array and return the array when the for loop is done.
In your loop, variable rand will be given the value equal to the value it's last iterations output, you need to return array of objects instead of single object to get desired result.
Related
I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?
function createArray(rows) {
for(let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}return rows;
}
createArray(5);
You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy.
Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.
Code
function createArray(rows) {
let arr = new Array(rows);
for (let i = 0; i < rows; i++) {
arr[i] = i + 1;
}
return arr;
}
console.log(createArray(5));
We can not use length property for number. create an empty array and then push values into that array until required size is achieved.
function createArray(rows) {
var arr = [];
for(let i = 1; i <= rows; i++) {
arr.push(i);
}return arr;
}
createArray(5);
I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this
function createArray(rows) {
const arr = []
for(let i = 1; i <= rows; i++) {
arr.push(i);
}
return arr;
}
console.log(createArray(5));
The problem is, that rows.length is not available on 5, because 5 is a number.
You have to use an array as parameter:
Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.
function createArray(rows) {
for (let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}
return rows;
}
const rows = Array(5).fill("hello");
createArray(rows);
I don't know, if this is the behaviour you want, if not, I misunderstood your question.
I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.
What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}
You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}
First function:
concatenate string and integer into one string.
insert result string into an array.
join all array's strings into one string.
Second function does the same, but instead of concatenation, it inserts 2 strings in the array.
Question: How do you figure out what function will allocate less memory?
One more question: How many strings in memory (for each iteration) for first function we will have? For example, for 1st iteration we will have only "a0" or "a0", "a" and "0"?
function joinLetters() {
var arr = [];
for(var i = 0; i < 10000; i++) {
arr.push('a' + i);
}
return arr.join('');
}
function joinLetters2() {
var arr = [];
for(var i = 0; i < 10000; i++) {
arr.push('a');
arr.push(i.toString());
}
return arr.join('');
}
joinLetters in the inner loop makes a single push, joinLetters2 does two push instead.
So you will have in the first case arr.length = 10000, while in the second arr.length = 20000.
Definitely you can expect the second function to be more memory expensive then the first.
Wondering why i needed to add 4 to the array length in order for it to print out the entire array in reverse?
before i added 4 it was just using the .length property and it was only printing out 6543.
thanks in advance!
function reverseArray(array) {
var newArray =[];
for(var i = 0; i <= array.length+4; i++) {
newArray += array.pop(i);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
array.pop removes (and returns) the last element. This affects the length of the array. The length is checked on every iteration, so since the array is getting shorter every time, the loop is ended early.
You can create a loop and pop items until it is empty, but another thing to take into account, is that it is the original array you are altering. I think a function like reverseArray shouldn't alter the array numbers that was passed to it if it returns another one. So a better solution would be a simple loop that iterates over all items without modifying the array.
function reverseArray(array)
{
var newArray =[];
for (var i = array.length-1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
console.log(numbers); // Should be unaltered.
If you don't mind modifying the array, you can use the reverse() method of the array:
var numbers = [1,2,3,4,5,6];
numbers.reverse();
console.log(numbers);
In Javascript, pop always removes the last element of the array. This shortens length, meaning that i and array.length were converging.
You can do a few things to avoid this behavior:
Store the original length when you start the loop: for (var i = 0 , l = array.length; i < l; i++)
Copy over values without modifying the original array
When you pop the items from the array, the item is removed from the array. As you increase the counter and decrease the length, they will meet halfway, so you get only half of the items.
Use push to put the items in the result. If you use += it will produce a string instead of an array.
If you use pop, then you can just loop while there are any items left in the array:
function reverseArray(array) {
var newArray = [];
while (array.length > 0) {
newArray.push(array.pop());
}
return newArray;
}
You can leave the original array unchanged by looping through it backwards and add items to the new array:
function reverseArray(array) {
var newArray = [];
for (var i = array.length - 1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
use following method for same output
function reverseArray(array)
{
var newArray =[];
var j = array.length-1;
for(var i = 0; i < array.length; i++)
{
newArray[j]= array[i]; j--;
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
I have the following code:
function bytesToMb(arr)
{
for(var i=0;i<arr.length;arr++)
{
var mbs= arr[i]/(1000*1000);
arr[i]=mbs;
}
return arr;
}
after the line arr[i]=mbs executes, the value of arr (the array object itself) becomes NAN.
why is that????
You are incrementing arr, arr + 1 = NaN because array is NaN; you ought to do i++ in your for loop instead...
You're using arr++ instead of i++ as the third clause in your for loop.
The type coercion from Array to Number leads to your NaN.
Change arr++ to i++
function bytesToMb(arr) {
for (var i = 0; i < arr.length; i++) {
var mbs = arr[i] / (1024 * 1024); // you should use 1024*1024 here to make it more precise if you need to.
arr[i] = mbs;
}
return arr;
}