outputting mulitple numbers into an array? - javascript

for (var i = 0; i < firstString.length; i++) {
newArray.push(i);
return newArray;
}
What code am i missing? Outputting [0], when i want to output [0,1,2,3,4,5,6]
What exactly am i doing with my code, since it's not what i think?
I've seen this --->
function someFunction(n){
var newArray = [];
for(var i=0; i < n.length; i++){
newArray.push(n[i]);
}
return newArray;
}
but i'm not looking to get the length of a function.

return will cause the code to exit the current method. Since you have put the return inside the for loop, your method is exiting after the first pass through the loop, thus returning only the output [0].
Move your return newArray; outside the loop.

Move the return statement out of the for loop, because it exits the function and the iteration.
for (var i = 0; i < firstString.length; i++) {
newArray.push(i);
}
return newArray;

Related

duplicate elements of an array in JavaScript

How to duplicate elements of an array in JavaScript and add them to the same array.
function duplicate(arr) {
// Write Logic here
var position,lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr[position] = arr[i];
position++;
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Please explain why the above code is not working. I'm getting "Incorrect Output" as error.
Also, I've come up with another way as shown below. But I'd like to know what's wrong with this approach.
function duplicate(arr) {
// Write Logic here
var lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr.push(arr[i]);
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Thank you
An alternative approach would be to use push to add elements to the end of the array. That way you don't need that extra position variable.
function duplicate(arr) {
const len = arr.length;
for (let i = 0; i < len; ++i) {
arr.push(arr[i]);
}
return arr;
}
let arr= [1, 2];
console.log(duplicate(arr));
You can achieve this by using Spread syntax (...)
Try this :
function clone(arr) {
arr.push(...arr);
return arr;
}
var arr=[1,2];
console.log(clone(arr));

Create array with function javascript

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.

Using JavaScript, how can I increment all items in an array and return the array?

There is one function that I am stuck on with incrementing all of the items in my array and returning the array. What to do now?
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++) {
arr[i] += 1;
return(arr);
}
}
You can simply use Array.prototype.map with an arrow function for this:
function incrementByOne(arr) {
return arr.map(value => value + 1);
}
console.log(incrementByOne([1,5,4,7,3]));
Your attempt was great, but your return arr; is too early. Mind that you're also modifying the array, instead of returning a copy with updated values. You could copy the array first with arr = [...arr];.
All I had to do was move the return outside the loop.
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return(arr);
}

why I am getting undefined result with for loop function?

why this code return undefined
I can't spot the reason
function findShort(s){
let splitted = s.split(' ');
let result = splitted[0].length ;
let looped
for (var i=0 ; i++ ; i<splitted.length){
looped = splitted[i].length;
if (looped < result) {return looped}else {return result }}
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
I am supposed to get numbers of smallest word
Your for loop condition and increment are inverted:
for (var i=0 ; i++ ; i<splitted.length){ ...
should instead be:
for (var i = 0; i < splitted.length; i++) { ...
You also have to fix your looping code as it returns in both branches of you inner if statement, which means only a single iteration will run.
If you want to return the length of the smallest word, do this:
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
for (let i = 0; i < splitted.length; i++) {
const looped = splitted[i].length;
if (looped < result) {
result = looped;
}
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
Or shorter using Array.prototype.reduce():
function findShortest(s) {
return s.split(/\s+/).reduce((out, x) => x.length < out ? x.length : out, s.length);
};
console.log(findShortest('bitcoin take over the world maybe who knows perhaps'));
Your for-loop implementation is wrong, it is supposed to be:
for (var i=0; i<splitted.length; i++)
Order of condition and increment is wrong in you for loop as well as the code inside the loop,
it will check for the first element only as you have a return in all conditions.
Here's the correct one
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
let looped
for (var i = 0; i < splitted.length; i++) {
looped = splitted[i].length;
if (looped < result) { result = looped }
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

Why this reverse function isn't working?

Why isn't this working?
ps. I don't want to use any other variable to make it work, and i don't want to use built in functions, just asking why THIS is not working?
function reverse(arr){
for(var i =0; i< arr.length; i++){
arr.push(arr[arr.length-i]);
}
return arr;
}
There are a lot of flaws in your code.
When you start pushing arr.push(arr[arr.length-i]); the array length increases, thereby, you won't get a consistency in the data.
This goes inside an infinite loop, as every time, the arr is ahead of its length.
It is better to use another variable and reverse, or you can use the built-in reverse() function. There's nothing wrong in having another variable and add temporary contents in it.
Solutions:
Using a temporary array:
function reverse(arr) {
var final = [];
for (var i = arr.length - 1; i >= 0; i--) {
final.push(arr[i]);
}
return final;
}
Using built-in function (Array.prototype.reverse()):
function reverse(arr) {
return arr.reverse();
}
Using few temporary variables:
a = [5,4,3,2,1];
function reverse(arr) {
var i = 0, j = arr.length - 1;
for (i = 0; i < j; i++, j--) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
console.log(reverse(a));
You're going to run out of memory. What you're doing is adding what was initially the last element of that array infinitely to the end of your array. Every time that you call arr.push(...) you increase arr.length by one. Your for loop will never be able to finish because i will never be less than arr.length
I don't want to use any other variable to make it work, and i don't want to use built in functions
You cannot.
Use temporary array for result
function reverse(arr) {
var res = []
for (var i = arr.length - 1; i > -1; i--) {
res.push(arr[i]);
}
return res;
}

Categories

Resources