Why is this code giving me an output of 5? [closed] - javascript

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 last year.
Improve this question
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
doubleNumbers.push(numbers[i] * 2)
}

It is because Array.push returns the new length of the array:
let arr = [];
console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2
You didn't log anything, but if you run code in the console it will print the outcome of the last statement.

From the documentation: the push() method adds one or more elements to the end of an array and returns the new length of the array.
If you run this in the developer console, it will log the last returned result.

Your Code output is okay
const numbers = [1,2,3,4,5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i+=1) {
doubleNumbers.push(numbers[i] * 2)
}
console.log(doubleNumbers)
Maybe You console the length of array

Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?
doubleNumbers.push(numbers[i] * 2)
should work just fine I believe.

Related

Javascript array with values [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 2 years ago.
Improve this question
The below code is a javascript interview question. I should get the output as [5,1,2,3,4]. Anyone can help me out this.
const input = [1,2,3,4,5]
const n = 4;
var output = []
console.log(output)
Without modifying the input array:
const input = [1,2,3,4,5]
const n = 4;
var output = []
output= [input[n],input.slice(0,n)].flat()
console.log(output)
From my understanding, the question is that when 'n' is a given index, you should be able to remove the element from the index n of the array and insert it at the very beginning of the array. As arrays are 0 based, it means that if n=4, then the element at nth index is 5 as per the given array.
In order to do that, you can do the following:
Use the splice method on the nth index and pass 1 as 2nd parameter, so you only remove the element at nth index.
Then use the unshift method on input to remove add the nth element at the beginning of the array. Unshift returns the length of the array, but you want the entire array to be stored in output.
So, you store the input array in the output variable.
Please run the below snippet for a better understanding. Let me know if my understanding of your question is not correct, so I can update my answer accordingly.
const input = [1,2,3,4,5]
const n = 4;
const [el] = input.splice(n,1); //array destructuring
input.unshift(el);
const output = input;
console.log(output)
const input = [1,2,3,4,5]
const n = 4
input.splice(0, 0, input[n])
input.splice(n+1, 1)
var output = [...input]
console.log(output)

Function with maximum possible sum of some of its k consecutive numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
As title, can anyone help me write a function return maximum possible sum of some of its k consecutive numbers
(numbers that follow each other in order.) of a given array of positive integers. Thank you!
I have read the answer but can anyone show me how its work? i just dont understand those code about?
There are several ways to do this, you can do this with the help of traditional for, Math.max(), indexOf() and Array#reduce.
First of all, you need to find the maximum value of your input array, then you should pop it and according to the iteration count, iterate to find the next maximum value. Then after you find all the maximum values you need to sum them up at last.
function maxOfSumChain(arr, length) {
const maxArr = [];
for (let i = 0; i < length; i++) {
const max = Math.max(...arr);
maxArr.push(max);
arr.splice(arr.indexOf(max), 1);
}
return maxArr.reduce((a, b) => a + b, 0);
}
console.log(maxOfSumChain([1, 3, 2, 6, 2], 3));
console.log(maxOfSumChain([1, 3, 2], 2));

storing values derived in a loop in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Please I need you guys help. I want do some calculations on the values that will be obtained from a loop but the calculation will depend on the last value the loop will compute. How do I store these values until the last value is computed by the loop and use the outcome to do further calculation on the previous values. Please I need a demonstrating example
I'm not exactly sure what you mean, but you could store every single value from the loop like this:
//First, make an empty array.
var values = [];
//Then, make your loop. This loop runs 50 times, but
//you can make it run however many times you want.
for (var i = 0; i < 50; i++) {
//This is where your loop does something with "i".
//You can do whatever you want with it, but I've chosen to square it.
values[i] = i * i;
}
//Now, "values" is an array with every calculation from the loop.
//Make another for loop, where "i" counts up to the length of "values".
for (var i = 0; i < values.length; i++) {
//The last result of the first loop is values[values.length - 1].
//here, do what you want with the values. I have chosen to divide each
//value by the last calculation of the function.
values[i] = values[i] / values[values.length - 1];
}
Hope this helped.

Where does this undefined value come from? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to compare two arrays and return a new array with any items only found in one of the two given arrays.
e.g. Result of comparing [1,2,3,4] and [1,2,3] should be: [4].
Problem is that, I get 'undefined' element after loop is executed.
function diff(arr1, arr2){
var newArr = [];
for(i=arr1[0]; i<=arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
console.log(newArr);
};
diff([1,2,3,4], [1,2,3]);
result of this is [4, undefined]. What am i doing wrong?
Your for loop has been defined incorrectly. It should start at i=0 and run until i<arr1.length
function diff(arr1, arr2){
var newArr = [];
for(i=0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
console.log(newArr);
};
By running until i<=arr1.length you are attempting to iterate once more than is needed, resulting in the addition of the final undefined value in the results array. As Mario Garcia says in comments, in the final iteration the loop will try to access arr[4] which doesn't exist, so is therefore undefined.
Your loop is wrong because your iterator doesn't start from 0 (to match the first array element), but from the value of the array at the index zero (which is number 1 in your case, but could be pretty much anything); and then you go out of index range when the iterator reaches the length of an array, in your case it's 4, and arr1[4] is undefined.
After fixing the loop start value and condition, we get:
function diff(arr1, arr2){
var newArr = [];
for(i = 0; i < arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
alert(newArr);
};
diff([1,2,3,4], [1,2,3]); // 4
diff([1,2,3,4,5], [1,3]); // 2, 4, 5

Increase performance for array manipulation [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 9 years ago.
Improve this question
I am using as certain code in JavaScript where I have to append a huge amount of data such as 10000 objects at a time to an array, and in a click event I again empty that array and reload that array with 10000 objects. Here is my code snippet:
where "Nodes" is an array populated from user datasource.
var Index = 0;
var _array = new Array();
for (var i = 0; i < this.Nodes.length; i++) {
if(this.Nodes.PLeft>this.Nodes.Cleft){
var temp = {};
temp["PLeft"] = this.Nodes.PLeft;
temp["CLeft"] = this.Nodes.CLeft;
temp["PWidth"] = this.Nodes.PWidth;
temp["CWidth"] = this.NodesCWidth;
temp["PTop"] = this.Nodes.PTop;
temp["CTop"] = this.Nodes.CTop;
temp["Height"] = this.Nodes.Height;
_array[Index++] = temp;
}
}
This works fine with Firefox, but for IE and Chrome the performance is too bad -- sometimes the browser crashes. I have also used push() method for array, but I did not find much difference in the performance. Does anyone have any idea on how to improve performance of array manipulation?
A few issues here. First, your loop does not access the individual elements of this.Nodes. Because you keep referring to this.Nodes.PLeft (for example), you wind up with the same probably-undefined value. You must specify the index, this.Nodes[idx].PLeft.
This, of course, begs the question: why do you need to loop some array and turn it into... an array? Can't you just use this.Nodes directly instead of transferring it all into _array first?
Another thing: to reduce the weight of a loop, get the max length outside of the loops conditional statement. Doing it within the conditional causes that value to be looked up every time, by putting it into a variable the lookup only happens once.
You can eliminate the temp object and add the new array element directly. Likewise, you can eliminate the redundant counter and use the for... loop's counter.
var _array = [];
var maxlen = this.Nodes.length;
for (var idx = 0; idx < maxlen ; idx++) {
if(this.Nodes[idx].PLeft > this.Nodes[idx].Cleft){
// use idx for the array key IF you want it to match with this.Nodes indexes
// if you don't care, use _array.length
_array[_array.length] = {
'PLeft':this.Nodes[idx].PLeft,
'CLeft':this.Nodes[idx].CLeft,
'PWidth':this.Nodes[idx].PWidth,
'CWidth':this.Nodes[idx].CWidth,
'PTop':this.Nodes[idx].PTop,
'CTop':this.Nodes[idx].CTop,
'Height':this.Nodes[idx].Height
};
}
}

Categories

Resources